-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

1
  • 4
    Yes it's possible. What have you tried so far? Commented Aug 7, 2019 at 16:17

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

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)

Comments

0

try this:

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

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

console.log(result);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.