James
James

Reputation: 33

Can you pass an array of index numbers to the array push method instead of specifying each index in push specifically

I want to create a new 2D array from another 2D array retaining specific columns from the original array that are defined in a variable.

I have a working version that uses hardcoded values of which columns from the original array to retain but I need a version that uses a variable.

var data = [
             [1,5,7,8,9,98,56],
             [4,7,8,9,2,55,88],
             [3,3,4,3,3,24,11]
            ];

 var indexes2Keep = [0,2,6]; 

 data.forEach(function(row) {
    slicedData.push( [ row[2], row[4], row[6] ] );
 });

Instead of having the columns hardcoded in the array push method how can I use the values of the variable indexes2Keep to give the same result.

thanks

Expected output is:

slicedData = [
         [1,7,56],
         [4,8,88],
         [3,4,11]
        ];

Upvotes: 3

Views: 361

Answers (3)

TheMaster
TheMaster

Reputation: 50406

You can use Array.map/Array.filter:

var data = [
         [1,5,7,8,9,98,56],
         [4,7,8,9,2,55,88],
         [3,3,4,3,3,24,11]
        ];

var indexes2Keep = [0,2,6]; 
var slicedData = data.map(function (row){
  return row.filter(function(_,i){
     return indexes2Keep.indexOf(i) !== -1
  })
})
//Alternatively
var slicedData2 = data.map(function (row){
  return indexes2Keep.map(function(i){
     return row[i]
  })
})
console.log(slicedData)
console.log(slicedData2)

Upvotes: 2

kshetline
kshetline

Reputation: 13672

You could use the map() function for this:

slicedData.push(indexes2Keep.map(index => row[index]));

Upvotes: 0

101arrowz
101arrowz

Reputation: 1905

Simply call .map on that array to map each index to the element at that index in the row.

data.forEach(function(row) {
    slicedData.push(indexes2Keep.map(function(index) {return row[index]}));
});

Upvotes: 0

Related Questions