search

Home  >  Q&A  >  body text

Add counted duplicate values ​​in filtred array using ...new Set

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粉186897465P粉186897465261 days ago449

reply all(1)I'll reply

  • P粉770375450

    P粉7703754502024-04-05 17:54:48

    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);

    reply
    0
  • Cancelreply