3

how do I use Javascript to turn this list:

var array = ["no yes", "maybe certainly"];

into this one:

var array2 = ["no", "yes", "maybe", "certainly"]
Tushar
87.4k21 gold badges164 silver badges182 bronze badges
asked Aug 7, 2015 at 5:39

3 Answers 3

4

It's better to use regex here, if there are chances of multiple spaces in the array elements.

  1. Join the array elements by space
  2. Extract non-space characters from string using regular expression

var array = [" no yes ", " maybe certainly "];
var array2 = array.join('').match(/\S+/g);
document.write(array2);
console.log(array2);

answered Aug 7, 2015 at 5:41
Sign up to request clarification or add additional context in comments.

9 Comments

Very simple, seems efficient.
@rrowland not so efficient jsperf.com/match-vs-split-22, as you can see split more faster than match
@Alexander You might want to recheck that again with updated answer. jsperf.com/match-vs-split-22/2
@Tushar as I see split faster than match jsperf.com/match-vs-split-22, and I can say much faster
@Alexander That is with the old code. I've updated code. Kindly check again on jsperf.com/match-vs-split-22/2
|
1

You can join all elements in array, and after split it to array, like so

// var array = ["no yes", "maybe certainly"];
var array = ["no yes ", " maybe certainly"];
var array2 = array.join('').trim().split(/\s+/g);
console.log(array2);

answered Aug 7, 2015 at 5:41

Comments

0
var array = ["no yes", "maybe certainly"]
answer = converfunction(array);
function converfunction(array){
return array.toString().replace(',',' ' ).split(' ')
}
answered Aug 7, 2015 at 5:55

1 Comment

Check with var array = [" no yes ", " maybe certainly "];

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.