0

I'm trying to find a way to access a part of an array with specific indexes, and the indexes are also in array. So, I have something like that:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

And I'm searching for an easy way to use arrIndexes to access this specific part of arr, so that my output would be simply ['one', 'three', 'five'].

3 Answers 3

1

You can do it with slightly less computational effort by using Array.prototype.map() instead:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

const res = arrIndexes.map(i=>arr[i])

console.log(res);

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer! This is optimal (y)
Thanks! That helped a lot, I knew that there was something easy which I could not think of :)
0

You can do it by using Array.prototype.filter() and includes() function. Try this-

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

const res = arr.filter((item, index) => arrIndexes.includes(index));

console.log(res);

Comments

0

you can using reduce function like this

 let newAr=arr.reduce((prev,curr,idx,arr)=>{
    if(arrIndexes.includes(idx)){
        prev.push(arr[idx]);
    }
    return prev;
},[])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.