find duplicate element on array 1

find duplicate element on array

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 } 

Here is what the above code is Doing:
1. The initial value is an empty object.
2. The first time the callback function is called, prevVal is the initial value, and item is the first item in the array.
3. The callback function checks if the object has a key with the name of the item. If it doesn’t, it means that the item is not repeated yet, so it sets the value of the key to 1.
4. The callback function returns the object.
5. The next time the callback function is called, prevVal is the object returned by the previous call, and item is the next item in the array.
6. The callback function checks if the object has a key with the name of the item. If it does, it means that the item is repeated, so it increases the value of the key by 1.
7. The callback function returns the object.
8. The process repeats until the end of the array.
9. The final value is the object returned by the last call of the callback function.

Similar Posts