0

As shown in the code below, I have an array and i push object inside in a loop. what I am trying to do is, sort it according to the value of delay property. I used the following code:

delayOfFeatures.sort((a, b) => a.delay - b.delay);

but the array does not change

code:

delayOfFeatures.push({ progSpace: progSpace, feature: feature, delay: delay });
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • You are sorting `delayOfFeatures` and the array you are pushing the values is `delayOfFeat` – Eddie Jun 29 '18 at 18:08
  • is delay a number? or a string with a number and some text? – Nina Scholz Jun 29 '18 at 18:10
  • Here is a similar question: https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript sort returns the sorted array, so var result = delayOfFeatures.sort((a, b) => a.delay - b.delay); result will have the sorted version, no loop needed. – user15741 Jun 29 '18 at 18:27
  • @user15741 - `.sort()` does return the array, but it also sorts the original in place so the array it is returning is the original array. There is no reason for an assignment. – jfriend00 Jun 29 '18 at 19:13
  • You will need to show us more of your code because there's no problem with `delayOfFeatures.sort((a, b) => a.delay - b.delay);`. That will sort the array via a numeric `delay` property just fine. So, not sure what your problem is. The code you show does not indicate any problem. – jfriend00 Jun 29 '18 at 19:14

1 Answers1

0

Here's a sample, where you can sort your features array according to the delay property in ascending or descending order.

class Feature {
  constructor(name, delay) {
    this._name = name;
    this._delay = delay;
  }
  
  get name() {
    return this._name;
  }
  
  get delay() {
    return this._delay;
  }
}

const features = [
   new Feature('Feature A', 1000),
   new Feature('Feature C', 500),
   new Feature('Feature B', 50),
   new Feature('Feature D', 1),
   new Feature('Feature E', 750),
];

// Ascending by delay
features.sort((a, b) => a.delay - b.delay);
console.log(features);

// Descending by delay
features.sort((a, b) => b.delay - a.delay);
console.log(features);
user7637745
  • 965
  • 2
  • 14
  • 27
  • How is your sorting any different than the `delayOfFeatures.sort((a, b) => a.delay - b.delay);` that the OP already has in their question? – jfriend00 Jun 29 '18 at 19:12
  • I tried to **make clear** to the OP what should be done in order to get the results the OP wants. That's why I filled up and array with simple, but a clear list of classes with a string and a number within each of them. Then, sort them in that 2 simple ways. – user7637745 Jun 29 '18 at 19:22