-1

I'm trying to sort an object and rebuild it based on highest to lowest values in Javascript. I've built a function which takes an array of numbers, counts them adds them up and then creates an object, my function for sorting doesn't seem to be working correctly,


const numbersToCount = [10, 10, 10, 5, 4, 3, 2, 2, 1]

function sort () {
    var counts = {}
    for (var i = 0; i < numbersToCount.length; i++) {
        var num = numbersToCount[i];
        counts[num] = counts[num] ? counts[num] + 1 : 1;
    }

    var numbersToSort = []

    for (var sort in counts) {
        numbersToSort.push([sort , counts[sort]])
    }

    numbersToSort.sort((a, b) => {
        return a[1] - b[1]
    })

    counts = {}
    numbersToSort.forEach((item) => {
        counts[item[0]]=item[1]
    })

    console.log(counts)
}

Currently, counts would output initally:

{
  '1': 1,
  '2': 2,
  '3': 1,
  '4': 1,
  '5': 1,
  '10': 3
}
Leandro Matilla
  • 911
  • 4
  • 14
Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • 1
    Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – Ashkan Feb 12 '20 at 20:06

2 Answers2

0

Object property iteration has separate rules for properties that look like array indexes: in that case they are always ordered in numerical, ascending order.

A quick fix is to agree with yourself to have those properties prefixed with some non-digit character, like an underscore:

Change:

counts[item[0]] =

to:

counts["_" + item[0]] =

Most would advise against using plain objects for keeping a certain order. Alternatively, use a Map, which always sticks to insertion order:

counts = new Map(numbersToSort);
trincot
  • 317,000
  • 35
  • 244
  • 286
0
const numbersToCount = [10, 10, 10, 5, 4, 3, 2, 2, 1];

const distinctNumbersToCount = [...new Set(numbersToCount)];
const sortNumbersToCount = distinctNumbersToCount.sort((a, b) => a - b); 

const response = sortNumbersToCount.map((number, index) =>{
    return { [index]: number }
})

console.log(response);

Output should be:

enter image description here

Leandro Matilla
  • 911
  • 4
  • 14