最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get array value by index jquery - Stack Overflow

programmeradmin0浏览0评论

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 0
Add a ment  | 

3 Answers 3

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论