I'm trying to sort an object of objects using Object.values(), sort() and map() into pages based on a nested value. It's works perfect in FF, but Chrome for some reason returns pages full of unsorted items.
Example structure of list:
{
1: {
id: 1,
rank: 10,
name: "foo"
},
2: {
id: 2,
rank: 24,
name: "bar"
},
3: {
id: 3,
rank: 11,
name: "baz"
},
...
}
Example:
const out = document.getElementById("out");
const sortBy = "rank";
const perPage = 10;
let list = {};
for (let i = 1; i < 50; i++) {
list[i] = {
id: i,
rank: rand(10, 200),
name: generateName(rand(6, 12))
}
}
const values = Object.values(list);
const pages = values.sort((a, b) => {
if (sortBy === "rank") {
return a.rank < b.rank;
} else if (sortBy === "name") {
return a.name > b.name;
}
})
.map((item, i) => {
return i % perPage === 0 ? values.slice(i, i + perPage) : null;
}).filter(page => page);
for (const page of pages) {
for (const item of page) {
out.value += `${item.rank}\n`;
}
}
// HELPERS
function rand(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}
function generateName(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
<textarea name="" id="out" cols="60" rows="30"></textarea>
agoes beforeb; positive, ifagoes afterb; and zero if they are equal (in terms of the sort criteria).