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]
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With