1

I'm trying to iterate through a for loop to sort an array 5 times.

let sortedCities = {};
for (let i = 0; i < 5; i++) {
  sortedCities[i] = darkSkyHelper.sortCities(info,unsortedCities,i);
  console.log(sortedCities[i]);
}
console.log(sortedCities);

static sortCities(info, cities, day) {
    let sortedCities = cities.sort(function(a,b) {
      return info[b].daily.data[day].precipProbability - info[a].daily.data[day].precipProbability;
    })
    return sortedCities;
  }

The first console.log displays the expected output for each loop while the second displays an object with each object value equaling the output from the last running of the loop

["cin", "cle", "col", "nya", "laa", "was", "tex"]
["was", "nya", "cle", "cin", "col", "laa", "tex"]
["cle", "cin", "was", "nya", "laa", "col", "tex"]
["laa", "col", "cle", "cin", "was", "nya", "tex"]
["col", "tex", "cle", "laa", "cin", "was", "nya"]

Object {..}
0: Array[7]
0: "col"
1: "tex"
2: "cle"
3: "laa"
4: "cin"
5: "was"
6: "nya"
length: 7
__proto__: Array[0]
1: Array[7]
0: "col"
1: "tex"
2: "cle"
3: "laa"
4: "cin"
5: "was"
6: "nya"
...
P. Jack
  • 455
  • 1
  • 5
  • 11
  • You've got five arrays shown, but you only loop through one in your code (`this.state.days`). Please include a [mcve] if you'd like more help. – Heretic Monkey Apr 05 '17 at 19:11
  • 1
    It sounds like `darkSkyHelper.sortCities` is returning a reference to the same array each time, just sorted differently. Hence each element in `sortedCities` is really the same array. – Jon B Apr 05 '17 at 19:21
  • See [How can you sort an array without mutating the original array?](http://stackoverflow.com/questions/9592740/how-can-you-sort-an-array-without-mutating-the-original-array) – JJJ Apr 05 '17 at 19:30

1 Answers1

1

Each time you call sortCities you're returning a reference to the same array, just sorted differently. You need to create a new array each time. There are several ways to do this, including slice:

static sortCities(info, cities, day) {
    let sortedCities = cities.sort(function(a,b) {
      return info[b].daily.data[day].precipProbability - info[a].daily.data[day].precipProbability;
    })
    return sortedCities.slice(0);
}
Jon B
  • 51,025
  • 31
  • 133
  • 161
  • 1
    Might be cleaner to sort a copy of the original array, instead of sorting the original (which mutates it) and then returning a copy. Also the new variable is unnecessary. – JJJ Apr 05 '17 at 19:33
  • 1
    @JJJ - perhaps. That would be `return cities.slice().sort(...)`. The OP can implement however in whatever way suits their style. – Jon B Apr 05 '17 at 19:37
  • Thank you both for your help! – P. Jack Apr 05 '17 at 19:42