javascript:通过索引从数组中获取子数组

时间:2018-01-04 07:54:52

标签: javascript

是否有单行代码通过索引从数组中获取子数组?

例如,假设我希望["a","c","e"]["a","b","c","d","e"]获得[0,2,4]。如何使用单行代码执行此操作?像["a","b","c","d","e"][0,2,4] ..

这样的东西

4 个答案:

答案 0 :(得分:8)

您可以使用map;



var array1 = ["a","b","c"];
var array2 = [0,2];
var array3 = array2.map(i => array1[i]);
console.log(array3);




答案 1 :(得分:3)

您可以使用Array#filterArray#includes

的组合



const array = ['a','b','c'];
console.log(array.filter((x,i) => [0,2].includes(i)));




答案 2 :(得分:3)

您可以使用filter



const arr = ['a', 'b', 'c'];
const indexes = [0, 2];

const result = arr.filter((elt, i) => indexes.indexOf(i) > -1);

document.body.innerHTML = result;




答案 3 :(得分:2)

您可以使用Array.prototype.reduce()

const arr = ['a', 'b', 'c', 'd', 'e'];
const indexes = [0, 2, 4];

const result = indexes.reduce((a, b)=> {
a.push(arr[b]);
return a;
}, []);

console.log(result);