Skip to content
Advertisement

How to count the no of occurences of a certain key in an array of object & append the count to each key’s value

How to count the no of occurences of the ‘value‘ key in a object inside an array & append the count to each value if any.

Here ‘a’ is the source data

var a = [
    { id: 1, value: "10000"},
    { id: 2, value: "20000"},
    { id: 3, value: "30000"},
    { id: 4, value: "10000"},
    { id: 5, value: "20000"},
    { id: 6, value: "40000"},
    { id: 7, value: "10000"},
    { id: 8, value: "70000"}
]

What i want to achieve is as following

result = [
    { id: 1, value: "10000"},
    { id: 2, value: "20000"},
    { id: 3, value: "30000"},
    { id: 4, value: "10000 (1)"},
    { id: 5, value: "20000 (1)"},
    { id: 6, value: "40000"},
    { id: 7, value: "10000 (2)"},
    { id: 8, value: "10000 (3)"}
]

Advertisement

Answer

var a = [
    { id: 1, value: '10000' },
    { id: 2, value: '20000' },
    { id: 3, value: '30000' },
    { id: 4, value: '10000' },
    { id: 5, value: '20000' },
    { id: 6, value: '40000' },
    { id: 7, value: '10000' },
    { id: 8, value: '10000' },
];

const hashMap = {};

const newArr = a.map((el) => {
    const temp = { ...el };
    if (!hashMap[el.value]) {
        hashMap[el.value] = 1;
    } else if (hashMap[el.value]) {
        temp.value = `${el.value} (${hashMap[el.value]})`;
        hashMap[el.value] += 1;
    }
    return temp;
});

console.log(newArr);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement