[removed] get subarray from an array by indexes

前端 未结 4 1347
执笔经年
执笔经年 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);

提交回复
热议问题