1

I have a large BST of objects (over 200k) and I need to group all of them by their name into single ones that combine the stocks and take the average of costs accordingly. If the stock reaches below or equal to zero I need to remove it from the BST as well. A sample of the input is

let x = [
{ name: 'Shoes of Negligible Looks', stock: -7, cost: '$52.81' },
{ name: 'Pants of Profound Intelligence', stock: 4, cost: '$26.07' },
{ name: 'Cape of Flaming Reputation', stock: 9, cost: '$87.81' },
{ name: 'Cape of Flaming Reputation', stock: 9, cost: '$87.81' },
{ name: 'Wand of Profound Reputation', stock: 17, cost: '$89.14' },
{ name: 'Cape of Icy Intelligence', stock: 15, cost: '$44.68' },
{ name: 'Pants of Negligible Distraction', stock: 28, cost: '$16.91' },
{ name: 'Ring of Profound Cunning', stock: 5, cost: '$88.25' },
]

In this sample I would need to combine the Cape of Flaming Reputation.

This is the comparator method I am using to compare the values of the nodes in my BST:

const comparatorFunction = (a, b) => String(a).localeCompare(String(b));

And I create the new BST & populate the array like this:

let bst = new BST(comparatorFunction);
for (let i = 0; i < x.length; i++) {
    bst.add(x[i]);
}

Then sort it into inOrder like this (im guessing this might be helpful when grouping):

let inOrderList = bst.inOrder();

Thanks in advance to anyone attempting this lengthy solution.

1 Answers1

0

I may be missing something, but here is how I did it with the help of some build-in JS functions, otherwise you may want to share what your BST implementation looks like.

function getUnique(arr) {

        // Getting unique items by name
        const newArr = Array.from(new Set(arr.map(x => x.name)))
            .sort((a, b) => {
               // Ascending sort
               return String(a).localeCompare(String(b));;
            });
        return newArr.map(x => {
            return arr.find(v => v.name === x);
        })
            // Filtering by stock!
        .filter(x => x.stock > 0);
}

const x = [
  { name: 'Shoes of Negligible Looks', stock: -7, cost: '$52.81' },
  { name: 'Pants of Profound Intelligence', stock: 4, cost: '$26.07' },
  { name: 'Cape of Flaming Reputation', stock: 9, cost: '$87.81' },
  { name: 'Cape of Flaming Reputation', stock: 9, cost: '$87.81' },
  { name: 'Wand of Profound Reputation', stock: 17, cost: '$89.14' },
  { name: 'Cape of Icy Intelligence', stock: 15, cost: '$44.68' },
  { name: 'Pants of Negligible Distraction', stock: 28, cost: '$16.91' },
  { name: 'Ring of Profound Cunning', stock: 5, cost: '$88.25' },
];

console.log(getUnique(x));