By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Want to find the amount of unique and duplicate objects from an array and list them in a specific way
JavaScript

Javascript – Want to find the amount of unique and duplicate objects from an array and list them in a specific way

Admin
Last updated: 2023/12/20 at 4:40 PM
Admin
Share
3 Min Read
Want to find the amount of unique and duplicate objects from an array and list them in a specific way

Problem:

[
 { "id":5,
  "name": "banana"
 },
 { "id":5,
  "name": "banana"
 },
 { "id":4,
  "name": "apple"
 },
 { "id":1,
  "name": "strawberry"
 },
 { "id":1,
  "name": "strawberry"
 }
]

const arrayMap = new Map(Array.map(i => [i.id, {...i, amount: 0 }]));

Contents
Problem:Solution:

Only have one method I’ve considered, such as mapping the array and assigning an amount per object using a loop but I’m not sure if this is a good way to do it, and the string part is still something I haven’t been able to figure out.

Order would be by highest ID number. The array could be seen as a shopping cart, you can have multiple bananas, and they’d just be listed under the same part of the string.

If you have 2 bananas with the ID 5, 1 apple with the ID 4, and 2 strawberries with the ID 1 it would display as such:

However, in my example the “banana” isn’t what makes it unique, it would be the ID. There would be no other bananas with different IDs, they would all be added with the same ID as duplicate objects.

"2x Banana, 1x Apple, 2x Strawberry"

Solution:

  1. Sort the array by ID, highest to lowest
  2. Reduce the sorted array to an object keyed by id with name and count values. Name conflicts if any can be resolved by first-seen.
  3. Map those entries to strings then join the whole thing together
const data = [{"id":5,"name":"banana"},{"id":5,"name":"banana"},{"id":4,"name":"apple"},{"id":1,"name":"strawberry"},{"id":1,"name":"strawberry"}];

const capitalise = (str) => str.replace(/\b[a-z]/g, (c) => c.toUpperCase());

const counts = data
  .toSorted((a, b) => b.id - a.id) // sort by ID highest to lowest
  .reduce((acc, { id, name }) => {
    acc[id] ??= {
      name,
      count: 0,
    };
    acc[id].count++;
    return acc;
  }, {});

const str = Object.values(counts)
  .map(({ name, count }) => `${count}x ${capitalise(name)}`)
  .join(", ");

console.log(str);

Expand snippet

If Array.prototype.toSorted() isn’t available, you can either

  • Not care about altering the order of the original array and just use Array.prototype.sort()
  • Break the original array reference using either [...data] or data.slice(0) then use .sort()

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article What is the correct usage of next.js app and pages directories? [closed] Javascript – What is the correct usage of next.js app and pages directories? [closed]
Next Article New to JavaScript, coming from Python, why is it not working? [duplicate] Javascript – New to JavaScript, coming from Python, why is it not working? [duplicate]
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?