1

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>

Demo Pen

1
  • 3
    Your sort comparator function is incorrect. The comparator is supposed to return a numeric value: negative, if a goes before b; positive, if a goes after b; and zero if they are equal (in terms of the sort criteria). Commented Oct 8, 2020 at 15:47

1 Answer 1

1

Thank you @Pointy. So the answer should be like this.

const pages = values.sort((a, b) => a.rank < b.rank ? 1 : -1)
Sign up to request clarification or add additional context in comments.

Comments

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.