Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements from an array based on the indices of another array in JavaScript?

This works, but I'm wondering if there is a better way to filter by index:

a = [10,20,30,40]
b = [1,3]
a.filter((x,i) => b.includes(i))
// [20, 40]
like image 716
nachocab Avatar asked Apr 30 '17 16:04

nachocab


People also ask

How do you sort an array of objects in JavaScript based on another array?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

Can you access an element in an array by using its index?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you sort an array based on another array?

Method 1 (Using Sorting and Binary Search)Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]. Initialize the output index ind as 0.

How do I extract an index from an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

Another way would be b.map(aIndex => a[aIndex]). If b is shorter than a this could also be faster. However if there are indexes in b that do not belong in a, you would end up with undefined "holes" in the array.

EDIT

Looking a bit into Array.includes, looks like it will run in O(n) for unsorted arrays. If we say A = a.length and B = b.length, your solution from the question should run in O(A * B). The second solution (with map) will run in O(B). To fix the undefined holes, you could add a .filter(element => typeof element !== 'undefined'). The final solution would then be b.map(i => a[i]).filter(e => typeof e !== 'undefined'). This now runs in O(2 * B), which should still be better than O(A * B).

like image 133
Freeman Lambda Avatar answered Oct 09 '22 12:10

Freeman Lambda