[英]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. 我想从另一个2D数组创建一个新的2D数组,保留原始数组中在变量中定义的特定列。
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. 不是在数组推送方法中对列进行硬编码,而是如何使用变量indices2Keep的值来提供相同的结果。
thanks 谢谢
Expected output is: 预期产出是:
slicedData = [
[1,7,56],
[4,8,88],
[3,4,11]
];
You can use Array.map
/ Array.filter
: 您可以使用
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. 只需在该数组上调用
.map
,即可将每个索引映射到该行中该索引处的元素。
data.forEach(function(row) {
slicedData.push(indexes2Keep.map(function(index) {return row[index]}));
});
您可以使用map()
函数:
slicedData.push(indexes2Keep.map(index => row[index]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.