Atom Vayalinkal
Atom Vayalinkal

Reputation: 2692

Get specific subarray using JavaScript

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?

Upvotes: 1

Views: 121

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 0

Ry-
Ry-

Reputation: 224913

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

Upvotes: 10

rawberry
rawberry

Reputation: 312

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++
}

Upvotes: 0

Related Questions