JSFiddle - React, Tailwind, and code Playground

by Sergei Sokolov

JavaScript

/**
 * для вопроса https://qna.habr.com/q/1049206
 * Как посчитать кол-во каждого элемента и для него посчитать сумму?
 */
const items = [
	{id: 'id1', price: 10},
  {id: 'id2', price: 20},
  {id: 'id3', price: 30},
  {id: 'id4', price: 40},
  {id: 'id5', price: 50}
]

const arr = ['id1', 'id1', 'id2', 'id3', 'id3'] // count id1: 2, id2: 1, id3: 2, price: 100
const counts = arr.reduce(
  (acc, c) => (acc[c] = (acc[c] ?? 0) + 1, acc),
  {}
); console.log("counts", counts);
const filtered =  items.filter(item => arr.includes(item.id))
const totalPrice = filtered.reduce((acc, el) => acc + el.price, 0);

const data = Object.fromEntries(
  Object.values(filtered)
    .map((item) => [
      item.id,
      {
        price: item.price,
        count: counts[item.id],
      },
    ]
  )
);

Object.entries(data)
  .forEach((item) => {
    const div = document.createElement("div");
    div.className = "item";
    ["count", "price"].forEach((name, i) => {
      const span = document.createElement("span");
      span.className = name;
      span.textContent = item[1][name];
      div.appendChild(span);
      if (0 === i) div.appendChild(document.createTextNode("x"));
    });
    document.body.appendChild(div);
  })