Add counted duplicate values ​​in filtred array using ...new Set
P粉186897465
P粉186897465 2024-04-04 19:03:41
0
1
447

I have an array with duplicate values, I get these values ​​from API, the following code uses...new Set() method to get all math comments without duplicate ones:< /p>

let notes = [];
if (props.getAllNotes()) {
    const maths = props.getAllNotes().map(item => {
        return item.subjects[0].math_note
    });
    notes = [...new Set(maths)];
}

This is what I have in props.getAllNotes():

notes = [15,16,10,13,15,16,10,18,11,13,15,16,10,18,11];

This is what I got:

notes = [15,16,10,13,18,11];

I want to add the count of each note in the final array notes, for example:

notes = [{10: 3}, {15: 5}...]

The notes method does this in the object, I need to do this to the final array notes where I use the ...new Set() method because I am Map through it to present some data

const counts = stars.reduce((acc, value) => ({
    ...acc,
    [value]: (acc[value] || 0) + 1
}), {});

P粉186897465
P粉186897465

reply all(1)
P粉770375450

After creating an object containing the frequency of each number, you can map its entries to create the desired array of objects.

let arr = [15,16,10,13,15,16,10,18,11,13,15,16,10,18,11];
let res = Object.entries(arr.reduce((acc, n) => {
  acc[n] = (acc[n] || 0) + 1;
  return acc;
}, {})).map(([k, v]) => ({[k]: v}));
console.log(res);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template