1

I have an javascript array that has the following values,

let arr = ["2","3","4","5","6"];

I have a second array that has three integers,

let index = [1,3,4];

How would I use JQuery (or Javascript) to use the array to get the index from arr, and add it to a new array. I want to add these strings to a new array.

indexArr = ["3","5","6"]

Thanks

0

3 Answers 3

1

Simple, just use Array.prototype.map():

let arr = ["2","3","4","5","6"];
let index = [1,3,4];

let indexArr = index.map(i => arr[i]);

console.log(indexArr);

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

Comments

1

You can do it with simple .map

let arr = ["2","3","4","5","6"];
let index = [1,3,4];
index.map(x=>arr[x]) //["3", "5", "6"]

Comments

0

Just use a loop. Personally I prefer this method over map because I find this easier to understand, but it's personal preference.

let arr = ["2","3","4","5","6"];
let index = [1,3,4];
let indexArr = [];
for(var i=0; i<index.length; i++) {
    indexArr.push(arr[index[i]]);
}
console.log(indexArr);

1 Comment

@dark_dab0 Great, glad I could help :)

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.