基于索引数组过滤数组

时间:2015-10-19 10:11:33

标签: javascript arrays underscore.js

首先,如果它重复(我搜索但没有找到这个简单的示例......),我会道歉,但我想根据arr1中的索引选择arr2的元素:

arr1 = [33,66,77,8,99]
arr2 = [2,0,3] 

我正在使用underscore.js,但未检索0索引(似乎被视为false):

res = _.filter(arr1, function(value, index){
    if(_.contains(arr2, index)){
        return index;
    }
});

返回:

# [77, 8]

我怎么能解决这个问题,是否有更简单的方法来过滤使用索引数组?我期待以下结果:

# [77, 33, 8]

6 个答案:

答案 0 :(得分:5)

最简单的方法是在_.map上使用arr2,就像这样

console.log(_.map(arr2, function (item) {
  return arr1[item];
}));
// [ 77, 33, 8 ]

在这里,我们迭代索引并从arr1获取相应的值并创建一个新数组。

如果您的环境支持ECMA Script 6的箭头功能,那么您只需执行

即可
console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]

此外,如果你的目标环境支持它们,你可以使用原生的Array.protoype.map本身,就像这样

console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]

答案 1 :(得分:2)

对我来说,最好的方法是使用过滤器

let z=[10,11,12,13,14,15,16,17,18,19]

let x=[0,3,7]

z.filter((el,i)=>x.some(j => i === j))
//result
[10, 13, 17]

答案 2 :(得分:1)

您将返回index,因此在您的情况下0被视为false。所以你需要返回true而不是

res = _.filter(arr1, function(value, index){
    if(_.contains(arr2, index)){
        return true;
    }
});

或只返回_.contains()

res = _.filter(arr1, function(value, index){
   return _.contains(arr2, index);
});

答案 3 :(得分:1)

String string = "[A100, test, message1, 6/24/2015 19:38, 6/24/2015 19:38],[A101, test, message2, 6/24/2015 19:38, 6/24/2015 19:38], [A102, test, message3, 6/24/2015 19:38, 6/24/2015 19:38],[A103, test, message4, 6/24/2015 19:38, 6/24/2015 19:38]"; String [] s1=string.split("\\],"); for(String s : s1) { System.out.println(s.replaceAll("[ \\[\\] ]", "")); } 返回一个布尔值。您应该从A100, test, message1, 6/24/2015 19:38, 6/24/2015 19:38 A101, test, message2, 6/24/2015 19:38, 6/24/2015 19:38 A102, test, message3, 6/24/2015 19:38, 6/24/2015 19:38 A103, test, message4, 6/24/2015 19:38, 6/24/2015 19:38 谓词而不是索引返回,因为_.containsfalsy value

filter

另外,JavaScript数组有一个原生0方法,因此您可以使用:

res = _.filter(arr1, function(value, index)) {
  return _.contains(arr2, index);
});

答案 4 :(得分:0)

将indices数组作为主循环迭代不是更好吗?

var arr1 = [33,66,77,8,99]
var arr2 = [2,0,3] 
var result = [];
for(var i=0; i<arr2.length; i++) {
   var index = arr2[i];
   result.push(arr1[index]);
}

console.log(result);

答案 5 :(得分:0)

可以在想要子集化的数组上使用 filter 方法。 filter 遍历数组并返回一个由通过测试的项目组成的新数组。测试是一个回调函数,在下面的示例中是一个匿名箭头函数,它接受必需的 currentValue 和可选的 index 参数。在下面的示例中,我使用 _ 作为第一个参数,因为它没有被使用,这样 linter 就不会将它突出显示为未使用:).
在回调函数中,数组的 includes 方法用于我们用作索引源的数组,以检查 arr1 的当前索引是否是所需索引的一部分。

let arr1 = [33, 66, 77, 8, 99];
let arr2 = [2, 0, 3];
let output = arr1.filter((_, index) => arr2.includes(index));
console.log("output", output);

相关问题