-5

// create origin array
var origin = [5, 7, 1, 0, 6, 5, 2, 7, 1, 5, 6];
var newArr = [];
// foreach array
origin.forEach((val, index) => {
   if( ??? ) { // who can help me solution in here
     newArr.push(val);
   } 
});
// show inner html
document.getElementById("result").innerHTML = newArr;
<div id="result"></div>

expected result new array is: [5,5,5,7,7,6,6,1,1,2,0].

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Vu Hao
  • 9
  • 1

3 Answers3

1
var origin = [5, 7, 1, 0, 6, 5, 2, 7, 1, 5, 6];    
origin.sort();
document.getElementById("result").innerHTML = origin

the "sort()" function is an inbuilt javascript function used to sort the arrays.

array.sort(compareFunction)

compareFunction: A function that defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

Karthik HG
  • 11
  • 2
0

You could take a Map for counting and sort by count and value descending.

var array = [5, 7, 1, 0, 6, 5, 2, 7, 1, 5, 6],
    count = array.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map);

array.sort((a, b) => count.get(b) - count.get(a) || b - a);

console.log(...array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can create object with count of each element and then sort by count and by value

// create origin array
var origin = [5, 7, 1, 0, 6, 5, 2, 7, 1, 5, 6];

var count = origin.reduce((acc,el)=>{
  if (!acc[el]){
    acc[el] = 0;
  }
  acc[el]++;
  return acc;
}, {});

console.log("count:", count)

origin.sort((a,b)=>{
  return count[b] - count[a] || b-a;
})

console.log("origin:", origin)
barbsan
  • 3,418
  • 11
  • 21
  • 28