📌  相关文章
📜  在数组上查找重复元素 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:24.490000             🧑  作者: Mango

代码示例1
const order = ["apple", "banana", "orange", "banana", "apple", "banana"];

const result = order.reduce(function (prevVal, item) {
    if (!prevVal[item]) {
        // if an object doesn't have a key yet, it means it wasn't repeated before
        prevVal[item] = 1;
    } else {
        // increase the number of repetitions by 1
        prevVal[item] += 1;
    }

    // and return the changed object
    return prevVal;
}, {}); // The initial value is an empty object.

console.log(result); // { apple: 2, banana: 3, orange: 1 }