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
8-Bit Borges
10.1k31 gold badges110 silver badges214 bronze badges
3 Answers 3
It's better to use regex here, if there are chances of multiple spaces in the array elements.
- Join the array elements by space
- 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
Tushar
87.4k21 gold badges164 silver badges182 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
rrowland
Very simple, seems efficient.
Oleksandr T.
@rrowland not so efficient jsperf.com/match-vs-split-22, as you can see
split more faster than matchTushar
@Alexander You might want to recheck that again with updated answer. jsperf.com/match-vs-split-22/2
Oleksandr T.
@Tushar as I see split faster than match jsperf.com/match-vs-split-22, and I can say much faster
Tushar
@Alexander That is with the old code. I've updated code. Kindly check again on jsperf.com/match-vs-split-22/2
|
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
Oleksandr T.
77.6k17 gold badges177 silver badges145 bronze badges
Comments
var array = ["no yes", "maybe certainly"]
answer = converfunction(array);
function converfunction(array){
return array.toString().replace(',',' ' ).split(' ')
}
1 Comment
Tushar
Check with
var array = [" no yes ", " maybe certainly "];lang-js