[英]compare element position from first array with number from second one
I am trying to compare the two arrays, more specifically to do something with values from the first one whose positions matches the numbers from second one. 我正在尝试比较两个数组,更具体地说,是对第一个数组中的值与第二个数组中的数字相匹配的值进行处理。
var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'],
positionNumberList = [0, 2, 4];
from above arrays value1 should be eq to 0 from second one, value3 = 2 .etc 从上面的数组中value1应该从第二个开始等于eq,value3 = 2 .etc
I started with the code below but can not get the position of the values from the first array. 我从下面的代码开始,但是无法从第一个数组获取值的位置。
for(j=0; j < valuesList.length; j++){
for(k=0; k < positionNumberList.length; k++){
//find matching values from first array
}
}
One of the solutions is use map()
method which applies a provided callback function for every item from array
. 解决方案之一是use
map()
方法,该方法对array
每个项目应用提供的回调函数。
var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'], positionNumberList = [0, 2, 4]; console.log(positionNumberList.map(function(item) { return valuesList[item]; }));
To do this you only need a single loop to iterate through the positionNumberList
array, and then access the items in valuesList
with the given indexes, like this: 为此,您只需要一个循环即可遍历
positionNumberList
数组,然后使用给定索引访问valuesList
的项目,如下所示:
var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5']; var positionNumberList = [0, 2, 4]; positionNumberList.forEach(function(index) { var value = valuesList[index]; console.log(value); });
Another approach: 另一种方法:
var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'],
positionNumberList = [0, 2, 4];
if(positionNumberList.length < valuesList.length){
for(var i=0; i < positionNumberList.length; i++){
console.log(positionNumberList[i],valuesList[i])
}
}
else{
for(var i=0; i < valuesList.length; i++){
console.log(valuesList[i],positionNumberList[i])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.