2 回答

TA贡献1803条经验 获得超3个赞
试图用评论进行解释,希望这会有所帮助。
const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);
const distinctColors = colors.reduce(
(distinct, color) =>
(distinct.indexOf(color) !== -1) ?
// ----------------^ Turnary to test for presence of current color in the accum []
distinct :
// ----^ It DOES exist, so return the current Accum array
[...distinct, color], []
// ---^ Is DOES NOT exist, return a new array of Accum + Color
// --------------------^ This initialises a new empty array into the accumulator
)
console.log(distinctColors)
只是添加此作为参考,为此使用一个集合要高效得多。
const colors = ['red', 'red', 'green', 'blue', 'green', 'yellow'];
console.log(colors);
const distinctColors = [...new Set(colors)];
console.log(distinctColors)
这是Set上的MDN文档。Javascript集
添加回答
举报