-2

If I have an array of strings:

array1 = ['mango', 'orange', 'apple','strawberry'];

and one array of indexes:

array2 = [1,3];

How can I create a new array with the strings in array1, based on the indexes in array2?

The new array would in this case look like this:

array3 = [orange, strawberry]
3
  • Iterate the array of indexes and use the value of those to index the first array and push those values into a new array, see answer/ Commented Sep 6, 2018 at 16:35
  • Map array2 with array1. Try that and add an attempt to your question. Commented Sep 6, 2018 at 16:36
  • 3
    It’s a simple map: const array3 = array2.map((index) => array1[index]). Commented Sep 6, 2018 at 16:36

1 Answer 1

0
//Declare a new array object
let newArray = [];

//iterate the array of index values, and use the value to index the first array and push into new array
for(let i = 0; i < array2.length; i++){
    newArray.push(array1[array2[i]]);
}

//log the results in new array
console.log(newArray);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.