Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Count number occurences in array and sorting them

I want to find occurrences of number in an array and then display the numbers and the occurrences with the numbers sorted in an ascending order like this:

let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

// {'-10': 2, '-8': 1, '1': 2, '2': 3, '6': 2, '9': 3, '10': 1}

I've found the occurrences of each number in the array by storing them in an object. When I tried console.log the numCount, all the numbers are sorted in an ascending order except for the negative numbers.

/*Find occurrences*/
let numCount = {};
for(let num of arr){
    numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
console.log(numCount);
//{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }

I look it up on how to sort object and it seems like the way to do it is by storing them in an array and then sort it. So that's what I tried:

/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
    sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
    return a[0] - b[0];
});

/*
console.log(sortedArray);
[
  [ '-10', 2 ],
  [ '-8', 1 ],
  [ '1', 2 ],
  [ '2', 3 ],
  [ '6', 2 ],
  [ '9', 3 ],
  [ '10', 1 ]
]
*/

This next method supposed to display them in an object sorted in ascending order but when I tried it, it displayed them with the negative numbers in the end of that object just like in the beginning. So this is the part where I'm stuck.

let sortedObject = {};
sortedArray.forEach(function(item){
    sortedObject[item[0]] = item[1];
})
/*console.log(sortedObject);
{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
*/

Full code:

let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

/*Find occurrences*/
let numCount = {};
for(let num of arr){
    numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}

/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
    sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
    return a[0] - b[0];
});


let sortedObject = {};
sortedArray.forEach(function(item){
    sortedObject[item[0]] = item[1];
})

console.log(sortedObject);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

There are rules about how properties/keys are sorted in an object and they are reliably ordered if you know the rules.

If the property is a positive number-like (in fact all properties are string actually even if they look like numbers), It will be sorted acceding. if not, it will sorted by the order of insertion. but how does object determine whether a property value is number-like or not?

Consider key '9' : first it is converted to a number which is 9. since it is positive then it is converted back to string which is '9'. same as the first value. so it is considered as a positive number-like for positive number-like.

Consider key '-10' : first it is converted to a number which is -10.

since it is not positive, it is considered as a string... and same for the rest.

So it is now clear that sorting for positive number-like properties was not really necessary at all. whether the input array is sorted or not, result will be the same and order is determined by rules.

solution:

Consider key '09' : first it is converted to a number which is 9. since it is positive then it is converted back to string which is '9'. not same as the first value. so it is considered as a string.

So let's put a '0' before every positive number-like and convert it to string after the sort.

sortedArray.forEach(function(item){
    let key = parseInt(item[0])>0 ? '0'+item[0] : item[0]
    sortedObject[key] = item[1];
})
//{ "-10": 2, "-8": 1, 01: 2, 02: 3, 06: 2, 09: 3, 010: 1 }

be aware that behavior of parseInt for numbers like 010 is different, since it assumes they are Octal.

Another and better solution is using map, read more about Maps and its differences with Objects here.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Possibly a Map would allow you to do what you want to do with the object whilst allowing you to set a key order.

let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];

/*Find occurrences*/
let numCount = new Map();
for(let num of arr){
  numCount.set(num, (numCount.get(num) ?? 0) + 1);
}

let sortedMap = new Map([...numCount.entries()].sort((a, b) => a[0] - b[0]));

console.log(sortedMap.get(-10));
console.log(...sortedMap.keys());
console.log(...sortedMap.values());

about 4 years ago · Juan Pablo Isaza Denunciar

0

Object properties aren't reliably ordered, and how an object is displayed will depend on the particular implementation of console.log.

If, oddly, it is just a matter of display then you could use, for example

const sortedArray = [[-10, 2], [-8, 1], [1, 2], [2, 3], [6, 2], [9, 3], [10, 1]];

let result = `{${sortedArray.map(el => `'${el[0]}': ${el[1]}`).join(', ')}}`;

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda