Reputation: 7122
I'm trying to take a list of cars and sort them alphabetically.
So I found this method to sort:
let cars = this.state.cars;
cars.sort(function (a, b) {
if (a.carName < b.carName) { return -1; }
if (a.carName > b.carName) { return 1; }
return 0;
})
console.log("items after sort: ", cars);
But when I write it out to the console, you can see the results below and they are not alphabetically sorted.
What could I be doing wrong?
Thanks!
items after sort:
List {size: 431, _origin: 0, _level: 5, _root: VNode, …}
size: 431
__altered: true
_level: 5
_origin: 0
_root: VNode
array: Array(4)
0: VNode {array: Array(32)}
0: {id: 1, carName: "Ford", isLocal: false, …}
1: {id: 2, carName: "BMW", isLocal: true, …}
2: {id: 3, carName: "Audi", isLocal: false,…}
3: {id: 4, carName: "Toyota", isLocal: false,…}
1: VNode {array: Array(32)}
2: VNode {array: Array(32)}
3: VNode {array: Array(32)}
Upvotes: 1
Views: 91
Reputation: 196236
Your log seems to imply that this data is from immutable.js.
By definition the data structure is .. immutable (cannot be modified). So running sort
on it will not modify the existing data but will return a sorted copy.
So try something like
let cars = this.state.cars;
const sortedCars = cars.sort(function (a, b) {
if (a.carName < b.carName) { return -1; }
if (a.carName > b.carName) { return 1; }
return 0;
})
console.log("items after sort: ", sortedCars);
or you could convert to normal js data structures with .toJS()
and then do what you want.
let cars = this.state.cars.toJS();
cars.sort(function (a, b) {
if (a.carName < b.carName) { return -1; }
if (a.carName > b.carName) { return 1; }
return 0;
})
console.log("items after sort: ", cars);
Upvotes: 2
Reputation: 69
Shortest possible code with ES6!
users.sort((a, b) => a. carName.localeCompare(b. carName))
String.prototype.localeCompare() basic support is universal!
Upvotes: 0