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"
...
3
  • You've got five arrays shown, but you only loop through one in your code (this.state.days). Please include a minimal reproducible example if you'd like more help. Commented Apr 5, 2017 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. Commented Apr 5, 2017 at 19:21
  • See How can you sort an array without mutating the original array? Commented Apr 5, 2017 at 19:30

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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 - perhaps. That would be return cities.slice().sort(...). The OP can implement however in whatever way suits their style.
Thank you both for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.