Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

javascript - Filter array based on an array of index

First I apologize if it's a duplicate (I searched but did not find this simple example...), but I want to select elements of arr1 based on the index in arr2:

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

I am using underscore.js but the 0 index is not retrieved (seems to be considered as false):

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

Which returns:

# [77, 8]

How could I fix this, and is there a simpler way to filter using an array of indexes? I am expecting the following result:

# [77, 33, 8]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest way is to use _.map on arr2, like this

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

Here, we iterate the indexes and fetching the corresponding values from arr1 and creating a new array.


Equivalent to the above, but perhaps a bit more advanced, is to use _.propertyOf instead of the anonymous function:

console.log(_.map(arr2, _.propertyOf(arr1)));
// [ 77, 33, 8 ]

If your environment supports ECMA Script 6's Arrow functions, then you can also do

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

Moreover, you can use the native Array.protoype.map itself, if your target environment supports them, like this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...