[removed] get subarray from an array by indexes

前端 未结 4 1314
执笔经年
执笔经年 2021-01-03 05:51

Is there a one-line code to get an subarray from an array by index?

For example, suppose I want to get [\"a\",\"c\",\"e\"] from [\"a\",\"b\",\"c\"

相关标签:
4条回答
  • 2021-01-03 06:26

    You can use 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);

    0 讨论(0)
  • 2021-01-03 06:27

    You could use map;

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

    0 讨论(0)
  • 2021-01-03 06:31

    You can use filter

    const arr = ['a', 'b', 'c'];
    const indexes = [0, 2];
    
    const result = arr.filter((elt, i) => indexes.indexOf(i) > -1);
    
    document.body.innerHTML = result;

    0 讨论(0)
  • 2021-01-03 06:36

    You can use a combination of Array#filter and Array#includes

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

    0 讨论(0)
提交回复
热议问题