0

I have an array like this :

 ["ID LONGITUDE LATITUDE", "0 77.139305 28.795975", "2 77.308929 28.486877", "4 73.820680 18.464110"]

I want to make it like this :

   var array= ["ID", "LONGITUDE", "LATITUDE", "0", "77.139305", "28.795975", "2", "77.308929", "28.486877", "4", "73.820680", "18.464110"]

How to do that ?

kalho
  • 75
  • 2
  • 9

3 Answers3

2

In case you actually have an array, here is how to do it succintly:

var rows = ["ID LONGITUDE LATITUDE", "0 77.139305 28.795975", "277.308929 28.486877", "4 73.820680 18.464110"];
[].concat.apply([], rows.map(function(row) { return row.split(' '); }))
// => ["ID", "LONGITUDE", "LATITUDE", "0", "77.139305", "28.795975", "277.308929", "28.486877", "4", "73.820680", "18.464110"]
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • sorry it changed nothing the output is this : http://prntscr.com/6izuoo and the code is this : http://prntscr.com/6izuvb – kalho Mar 20 '15 at 06:33
  • From what I can see in the screenshot, you don't actually have spaces as you say in your title, you have *tabs*. Change `row.split(' ')` into `row.split(/\s+/)` to allow for any kind of whitespace. – Amadan Mar 20 '15 at 06:35
2

Try the following code:

var string_array =  ["ID LONGITUDE LATITUDE", "0 77.139305 28.795975", "2 77.308929 28.486877", "4 73.820680 18.464110"];

var new_string_array = [];

for(var strings in string_array) {
    var x = string_array[strings].split(" ");
    for(var sub_string in x) {
        new_string_array.push(x[sub_string]);
    }
}

alert(new_string_array);

Here is the fiddle

Gulfaraz Rahman
  • 417
  • 4
  • 13
1

It may be done with reduce

["ID LONGITUDE LATITUDE", "0 77.139305 28.795975", "2 77.308929 28.486877", "4 73.820680 18.464110"].reduce(function(arr, item) {

  item.split(' ').forEach(function(item) {
    arr.push(item)
  });

  return arr;
}, [])
Evgeniy
  • 2,915
  • 3
  • 21
  • 35