Home > Blockchain >  How do you sort an array by only using specific elements?
How do you sort an array by only using specific elements?

Time:09-24

I'm using an array as a temporary inventory (as part of a game). There are items and values, each being a string. They are always followed.

The value or quantity determines how much of that item you have.

For example: inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

In the example above you would have a banana with a quantity of 5

My goal is to sort the array by quantity. So a function could return ['berries', '8','bananas', '5' 'apples','3']

Thanks!

CodePudding user response:

As others have pointed out, this seems like A Bad Idea™ and you really should consider using a more suitable data structure.

Having said that, there are ways to do it.

In the snippet below I first convert the array to an object via reduce so you end up with a structure like this (which you should consider using in the first place):

{
  bananas: 5,
  berries: 8,
  apples: 3
}

I then sort that object's entries, producing a sorted array of pairs:

[
  ['apples', 3],
  ['bananas', 5],
  ['berries', 8],
]

Finally, flattening that array produces the result you're after:

['apples', 3, 'bananas', 5, 'berries', 8]

Again, I agree with the comments above suggesting that this calls for a more suitable data structure, but if you have to do it this way for some reason you could.

const inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

const quantities = inventoryArray.reduce((acc, item, index, arr) => {
  // skip odd indices (the quantities)
  if (index % 2 === 1) {
    return acc;
  }
  
  // add the product and qty (index   1) to the result
  return {
    ...acc,
    [item]: Number(arr[index   1])
  }
}, {});

// sort the key value pairs
const arr = Object.entries(quantities).sort(([, qtyA], [, qtyB]) => qtyA - qtyB);

console.log(arr.flat());

  • Related