skip to Main Content
[
 { "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 }]));

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"

2

Answers


  1. You can do it by looping through the array. For example,

    const data = [
      { "id": 1, "name": "item1" },
      { "id": 2, "name": "item1" },
      { "id": 3, "name": "item3" },
      { "id": 4, "name": "xd" }
    ];
    
    // Create an object to store item counts
    const itemCounts = {};
    
    data.forEach((item) => {
      const itemName = item.name;
      itemCounts[itemName] = (itemCounts[itemName] || 0) + 1;
    });
    
    const sortedItems = Object.entries(itemCounts)
      .sort((a, b) => b[1] - a[1])
      .map(([itemName, count]) => `${count}x ${itemName}`)
      .join(' ');
    
    console.log(resultString); 
    
    Login or Signup to reply.
    1. Sort the array by ID, highest to lowest
    2. Reduce the sorted array to an object keyed by name with count values.
    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 counts = data
      .toSorted((a, b) => b.id - a.id) // sort by ID highest to lowest
      .reduce((acc, { name }) => {
        acc[name] = (acc[name] ?? 0) + 1;
        return acc;
      }, {});
    
    const str = Object.entries(counts)
      .map(([name, count]) => `${count}x ${name}`)
      .join(", ");
    
    console.log(str);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search