Filter array based on index array

At first, I apologize if this is a duplicate (I searched, but did not find this simple example ...), but I want to select elements arr1based on the index in arr2:

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

I use underscore.js, but the index is 0not retrieved (it appears to be considered false):

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

What returns:

# [77, 8]

How can I fix this, and is there an easier way to filter using an array of indexes? I expect the following result:

# [77, 33, 8]
+4
source share
4 answers

The easiest way is to use _.mapon arr2, like this

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

arr1 .


ECMA Script 6 Arrow,

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

, Array.protoype.map, , ,

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

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);
});
+1

_.contains . filter, , 0 .

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

, JavaScript filter, :

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

?

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);
0

Source: https://habr.com/ru/post/1612222/


All Articles