8-Bit Borges
8-Bit Borges

Reputation: 10033

javascript - transforming arrays

how do I use Javascript to turn this list:

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

into this one:

var array2 = ["no", "yes", "maybe", "certainly"]

Upvotes: 3

Views: 63

Answers (3)

Tushar
Tushar

Reputation: 87203

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);

Upvotes: 4

Oleksandr T.
Oleksandr T.

Reputation: 77482

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);

Upvotes: 1

tech savy
tech savy

Reputation: 193

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

answer = converfunction(array);

function converfunction(array){
return array.toString().replace(',',' ' ).split(' ')
}

Upvotes: 0

Related Questions