Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Pushing one array element to the end

I'm trying to rearrange sorting of an array. Let's say I have the following structure

    const array = [{
     location: 'Table 2',
     data: {..}
    }, {
     location: 'Unassigned',
     data: {..}
    }, {
     location: 'Table 1',
     data: {..}
}
];

What's the proper way of moving 'Table 1' to index 0, 'Table 2' right after it (keep same order for Table 3, 4, etc), and 'Unassigned' always to the end. Preferably with lodash.

Here's what I tried so far

  forEach(allItemsSorted, (item, index) => {
    const total = allItemsSorted.length;
    let hasUnassigned = false;
    if (item.location === 'Unassigned') {
      allItemsSorted[total] = item;
      hasUnassigned = true;
    }
    if (hasUnassigned && index === total) {
      return;
    }
    allItemsSorted[index] = item;
  })
like image 447
Alex Avatar asked May 27 '26 15:05

Alex


1 Answers

You can use Array.sort() - always move the Unassigned to the end (the two ifs). Sort the other items using String.localeCompare() with the numeric option.

Note: I use array spread - [...array] - to clone the array, so the original won't be mutated. You can skip that, if you want to change the original array.

const array = [{location:'Table 27'}, {location:'Table 2'}, {location: 'Unassigned'}, {location: 'Table 11'}];

const result = [...array].sort(({ location: a }, { location: b }) => {
  if(a === 'Unassigned') return 1;
  if(b === 'Unassigned') return -1;
  
  return a.localeCompare(b, undefined, {numeric: true});
});

console.log(result);
like image 71
Ori Drori Avatar answered May 30 '26 06:05

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!