简体   繁体   中英

get array value by index jquery

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

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM