-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
  • 2,091
  • 3
  • 35
  • 78

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
  • 62,582
  • 25
  • 126
  • 161
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,730
  • 2
  • 21
  • 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
  • 34,175
  • 38
  • 176
  • 338
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,446
  • 1
  • 14
  • 23
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);