-4

I have the following array in javascript:

DATA[
[ 3, "Name1" ],
[ 5, "Name2" ],
[ 10, "Name3" ],
[ 55, "Name4" ]
]

I would like to convert it to:

DATA[ "Name1", "Name2", "Name3", "Name4" ]

Is it possible in javascript?

Thanks

myTest532 myTest532
  • 1,815
  • 1
  • 19
  • 48

5 Answers5

1

There's a few ways to do this, but here's one:

for(var i=0;i<DATA.length;i++){
  DATA[i] = DATA[i][1];//only grab the 2nd item in the array
}
scunliffe
  • 60,441
  • 24
  • 124
  • 159
1

Simple use-case for Array.prototype.map

let data = [
  [3, "Name1"],
  [5, "Name2"],
  [10, "Name3"],
  [55, "Name4"]
];

data = data.map(arr => arr[1]);

console.log(data);
Tom O.
  • 5,449
  • 2
  • 20
  • 35
0

Simply use a map and grab the second item of each child array to build the new array.

const DATA = [
  [ 3, "Name1" ],
  [ 5, "Name2" ],
  [ 10, "Name3" ],
  [ 55, "Name4" ]
]

const newArr = DATA.map(i => i[1])

console.log(newArr)
Get Off My Lawn
  • 30,739
  • 34
  • 150
  • 294
0

try this:

let data = [
  [3, "Name1"],
  [5, "Name2"],
  [10, "Name3"],
  [55, "Name4"]
];

const result =  data.map(([k, v])=>v);

console.log(result);
Ghoul Ahmed
  • 4,012
  • 1
  • 13
  • 22
0

Try this :

var data =[[ 3, "Name1" ],[ 5, "Name2" ],[ 10, "Name3" ],[ 55, "Name4" ]];
var newdata=[];
data.forEach(function(element){
    if(Array.isArray(element)){
        newdata.push(element[1]);
    }
});
console.log(newdata);