简体   繁体   中英

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

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) 

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

您可以使用map()函数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM