0

I am performing an Array.sort with the compare method like so:

orderNotes(notes){
    function compare(a, b) {
      const noteA =a.updatedAt
      const noteB =b.updatedAt

      let comparison = 0;
      if (noteA < noteB) {
        comparison = 1;
      } else if (noteA > noteB) {
        comparison = -1;
      }
      return comparison;
    }
    return notes.sort(compare)
  }

Now since I need to sort the array anyway and loop through each element with the Array.sort, I want to use this chance to check if the note.id matches on the neighboring note, and remove the duplicate from the array (doesn't matter which one). This will save me the trouble to loop again just to check duplication.

Is it possible to alter the array inside the compare() function and remove the duplicate?

Best

KasparTr
  • 2,328
  • 5
  • 26
  • 55
  • The `.sort()` function can only sort the array. You can try using `.filter()` to remove elements. Something like: https://stackoverflow.com/q/1960473 – gen_Eric Dec 04 '18 at 16:52

2 Answers2

1

Is it possible to alter the array inside the compare() function and remove the duplicate?

You could .splice(...) the element out of it if it doesn't match, but actually this:

This will save me the trouble to loop again just to check duplication.

Is a missconception. Looping an array and doing two tasks will only be slightly faster than two loops, as only the looping part gets duplicated, not the tasks done in the loop. Therefore just:

  const ids = new Set;
  const result = array
    .filter(it => ids.has(it.id) && ids.add(it.id))
    .sort((a, b) => a.updatedAt - b.updatedAt);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

It might be a simpler solution to use Array.prototype.reduce to remove the duplicates in an additional step instead of while sorting:

//Starting with your ordered array
var ordered = [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 8, 9, 9, 9];

//Now create a new array excluding the duplicates
var orderedAndUnique = ordered.reduce((accum, el) => {
  if (accum.indexOf(el) == -1) {
    accum.push(el);
    return accum;
  }
  return accum;
}, []);

console.log(orderedAndUnique);
Tom O.
  • 5,730
  • 2
  • 21
  • 35