Home > other >  Mapping over a Javascript array, to count distinct values
Mapping over a Javascript array, to count distinct values

Time:05-25

I'm struggling to find way to map over this set of records, and attach the count to the object itself. Here is a sample list of data, I need to return each of the 3 users at the end, however I need to also return the count. As an example, the returned data from the response below should attach the user_song_count like so.

{
user_song_count: 2,
user_song: {
  user_id: 2,
  username: 'tommy.g',
}

Sample data

    {
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 1,
      username: 'billy.m',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 3,
      username: 'sally.e',
    },
    user_time: null,
    user_scene: null,
  }

CodePudding user response:

You can use Array.prototype.reduce to merge the objects with similar user_id.

const data = [
  {
    user_song: { user_id: 2, username: "tommy.g" },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: { user_id: 1, username: "billy.m" },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: { user_id: 2, username: "tommy.g" },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: { user_id: 3, username: "sally.e" },
    user_time: null,
    user_scene: null,
  },
];

const result = Object.values(
  data.reduce((r, d) => {
    if (!r[d.user_song.user_id]) {
      r[d.user_song.user_id] = { ...d, user_song_count: 0 };
    }
    r[d.user_song.user_id].user_song_count  = 1;
    return r;
  }, {})
);

console.log(result);

Additional Documentation:

CodePudding user response:

let sample_data = [{
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 1,
      username: 'billy.m',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 3,
      username: 'sally.e',
    },
    user_time: null,
    user_scene: null,
  }];

let result = sample_data.map ( function (x) {
    x.user_song_count = sample_data.filter ( y => y.user_song.user_id == x.user_song.user_id ).length;
    return x;
});

console.log (result);

  • Related