Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i improve this Javascript code that arrange the array in ordered list first and put them in an array of array with same value?

Can this code be Improved? It arrange our array into sorted list(sortedArray) first and, the finalArray takes the final result;Example finalArray = [[1,1,1,1][2,2,2]…]

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
let sortedArray = []
let finalArray = []

sortedArray = array.sort((a, b) => {
  if (a > b) return 1;
  if (a < b) return -1;
  return sortedArray.push(a - b);
});

finalArray = sortedArray.reduce((item, index) => {
  if (typeof item.last === 'undefined' || item.last !== index) {
    item.last = index;
    item.sortedArray.push([]);
  }
  item.sortedArray[item.sortedArray.length - 1].push(index);
  return item;

}, {
  sortedArray: []
}).sortedArray;
console.log(finalArray);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is a shorter version than yours and more readable than Nina’s

let array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

const finalArray = array.slice(0) // copy the array
  .reduce((acc,cur) => {
    const idx = acc.findIndex(item => item[0] === cur);
    if (idx !=-1) acc[idx].push(cur); // just push
    else acc.push([cur]); // push as array
    return acc
  },[])
  .sort(([a],[b]) => a-b); // sort on the first entry

console.log(finalArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading