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)"}
]
CodePudding user response:
You can use Array.map and save the value
I think this is more readable than using Map
const values = {},
b = a.map(({ id, value }) => {
values[value] = (values[value] || 0) 1; // assign and/or increment
if (values[value] > 1) value = ` (${values[value]-1})`;
return { id, value };
});
console.log(b)
<script>
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"}
]</script>
CodePudding user response:
You can make use of Map
as a place where you can store count of number of occurence.
const 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' },
];
const map = new Map();
const result = a.map((o) => {
const valueInMap = map.get(o.value);
map.set(o.value, (valueInMap ?? 0) 1);
return valueInMap ? { ...o, value: `${o.value} (${valueInMap})` } : o;
});
console.log(result);
CodePudding user response:
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);