Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
How do you sort an array by only using specific elements?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!