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
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
Share Improve this question asked Jun 30, 2017 at 11:51 dark_dab0dark_dab0 2431 gold badge3 silver badges9 bronze badges 03 Answers
Reset to default 1Simple, 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);
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"]
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);