'Counting arrays by distinct value
I have an array of arrays. Each contains a list of information along with an id as below:
let array = [
['value1', 'value2', 'value3', 'value4', 'value5', 'id_1'],
['value1', 'value2', 'value3', 'value4', 'value5', 'id_1'],
['value7', 'value8', 'value9', 'value10', 'value11', 'id_3'],
['value20', 'value21', 'value22', 'value23', 'value24', 'id_4'],
['value20', 'value21', 'value22', 'value23', 'value24', 'id_5'],
];
I want to count the distinct instances of each array. When comparing two arrays, if all indexes are the same, including the id, then this means the array is a duplicate and only 1 instance should be counted.
If all indexes are the same, but the id is different, then this means that this is a distinct instance of the array and should be added to the count.
The information needs to be displayed in an object as below. I am struggling to visualise how to accomplish this, my current approach is to remove the ids from arrays, add these to the object and then figure out a way to count the unique instances - but unsure if this is the most effective method.
let obj = [
{
array=['value1', 'value2', 'value3', 'value4', 'value5'],
count=1
},
{
array=['value7', 'value8', 'value9', 'value10', 'value11'],
count=1
},
{
array=['value20', 'value21', 'value22', 'value23', 'value24'],
count=2
}
];
Solution 1:[1]
You can use something like this.
I iterated over the array, joined all array values except the last one (id) and then used the joined string as a hash value for my map object and then checked if the id is is different then update the count else dont change
const arr = [
['value1', 'value2', 'value3', 'value4', 'value5', 'id_1'],
['value1', 'value2', 'value3', 'value4', 'value5', 'id_1'],
['value7', 'value8', 'value9', 'value10', 'value11', 'id_3'],
['value20', 'value21', 'value22', 'value23', 'value24', 'id_4'],
['value20', 'value21', 'value22', 'value23', 'value24', 'id_5'],
];
const map = {};
arr.forEach(x => {
const key = x.slice(0, -1).join('-');
const id = x.at(-1);
if (!map[key]) {
map[key] = {
count: 1,
id,
};
} else {
if (id !== map[key].id)
map[key].count++;
}
});
console.log(map);
const obj = Object.entries(map).map(([k, v]) => ({
array: k.split('-'),
count: v.count
}))
console.log(obj);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EzioMercer |
