UPDATE
Some of the commentators make a good point that the original array is being mutated in order to break early inside the .reduce()
logic.
Therefore, I've modified the answer slightly by adding a .slice(0)
before calling a follow-on .reduce()
step, yielding a copy of the original array.
NOTE: Similar ops that accomplish the same task are slice()
(less explicit), and spread operator [...array]
(slightly less performant). Bear in mind, all of these add an additional constant factor of linear time to the overall runtime + 1*(O(1)).
The copy, serves to preserve the original array from the eventual mutation that causes ejection from iteration.
const array = ['apple', '-pen', '-pineapple', '-pen'];
const x = array
.slice(0) // create copy of "array" for iterating
.reduce((acc, curr, i, arr) => {
if (i === 2) arr.splice(1); // eject early by mutating iterated copy
return (acc += curr);
}, '');
console.log("x: ", x, "
original Arr: ", array);
// x: apple-pen-pineapple
// original Arr: ['apple', '-pen', '-pineapple', '-pen']
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…