Update: It seems like the issue is related to how the chrome console handles object evaluation, as pointed out by jsN00b.
original source
I am currently sorting an array by name and then by age, and logging the array three times: First right after initialization, Second and third times are after sorting the array by name and then age respectively.
However, the first console.log()
call displays the array in its sorted state, whereas I was expecting it to show the array in its unsorted state.
Not sure if this behavior is due to the way JavaScript manages arrays in memory or if it's a bug?
Code:
function byField(field) {
return (objA, objB) => (objA[field] > objB[field] ? 1 : -1);
}
let users = [
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
];
console.log(users);
users.sort(byField("name"));
console.log(users);
users.sort(byField("age"));
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Expected output:
//unsorted
[
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
];
//by name
[
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
{ name: "Pete", age: 18, surname: "Peterson" },
];
//by age
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
Actual Output:
//unsorted
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
//by name
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];
//by age
[
{ name: "Pete", age: 18, surname: "Peterson" },
{ name: "Ann", age: 19, surname: "Hathaway" },
{ name: "John", age: 20, surname: "Johnson" },
];