1

Suppose I have an array

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]

and I have another array of the same size:

var select = [0,1,1,1,0]

How can I get the array fruits[select] = ["Orange", "Lemon", "Apple"], if this makes sense. This is something I can easily do in some other languages (e.g. R), but is this easily doable in JS?

1
  • Maybe by passing a loop in which if( i === 1) so enter the value. Commented May 31, 2018 at 21:03

3 Answers 3

10

Array.prototype.filter passes its predicate an index, so:

fruits.filter((fruit, i) => select[i])

let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
let select = [0, 1, 1, 1, 0];
let result = fruits.filter((fruit, i) => select[i]);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Not the way you want to do it. However, something like below should work, granted the syntax might not be exactly correct.

var x = 0;
var selectedFruits = []
foreach(var bit in select)
{
    if(bit == 1)
       selectedFruits.Add(fruits[x])
     x++
}

Comments

0

Another solution could be to shift the values of select for filtering. This mutates select and needs a binding of this array.

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"],
    select = [0, 1, 1, 1, 0],
    selected = fruits.filter([].shift.bind(select));
    
console.log(selected);

Or just without binding but with thisArg of Array#filter

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"],
    select = [0, 1, 1, 1, 0],
    selected = fruits.filter([].shift, select);
    
console.log(selected);

4 Comments

That's really clever! Not obvious what's going on, but really neat once you figure it out.
This does take quadratic time on arrays that are large enough on existing JS engines, mind.
@Ry-, just O(2n) (which is still O(n)), one for fruits and one for select. no quadratic time.
@NinaScholz: shift() takes time proportional to the size of the array. (V8 optimizes it to not move anything for small arrays, though.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.