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"];
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.
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.
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.
Use .map
:
let resultArr = indexArr.map(i => fruitier[i])
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