Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of values based on an array of indexes?

I have a set of two arrays. One contains some fruit values as strings, the other one contains some random numbers. Here I considered the number arrays are the indexes of the fruits array. How to get a new array of fruits given the numbers in the index array?

Sample code:

var resultArr = [];
var fruitier = ["apple", "orange", "grapes", "pineapple", "fig", "banana", "jackfruit", "pomegranate"];
var indexArr = [0, 2, 4];

Output:

resultArr = ["apple", "grapes", "fig"];
like image 914
Sathya Avatar asked Nov 04 '16 04:11

Sathya


People also ask

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 find the index of an array based on value?

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.

How do I find all the values of an array?

To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements.


1 Answers

Use .map:

let resultArr = indexArr.map(i => fruitier[i])
like image 191
Aᴍɪʀ Avatar answered Sep 19 '22 21:09

Aᴍɪʀ