0

My function is sorting a Array by age, but its not working for some reason?

Other code so you know what im calling, array name etc.

var employeeA = new Array();
var employee = new Object();
var employeeList = [];
var employeeListA = [];
var name;
var age;
var position;
var type = 3;
var canvas;
var ctx;

function setupCanvas() {
    //alert("1");
    canvas = document.getElementById("employeeRecords");
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        ctx.fillStyle = "lightblue";
        ctx.rect(0, 0, 500, 500);
        ctx.fill();
    }

Heres the Sort Age code:

function sortAge() {
    type = 1;
    employeeList.forEach(function(empl) {
        name = empl.name;
        age = empl.age;
        position = empl.position;
        employeeA = new Array(age, name, position);
        employeeListA.push(employeeA);
    });
    var y = employeeListA.length;
    if (y > 1) {
        employeeListA.sort();
    }
}

this code is being called for the sorting buttons

function arrayButtons() {
    employeeListA = [];
    if (type === 0) {
        sortName();
    } else {

        if (type === 1) {
            sortAge();
        } else {
            employeeList.forEach(function(empl) {
                name = empl.name;
                age = empl.age;
                position = empl.position;
                employeeA = new Array(name, age, position);
                employeeListA.push(employeeA);

            });

Thanks for the help! Appreciate it :D

Pointy
  • 405,095
  • 59
  • 585
  • 614
Lachlan M
  • 45
  • 1
  • 7
  • The `.sort()` method can be passed a callback function, and that would allow you to compare parts of the array elements directly. – Pointy Sep 19 '18 at 13:55
  • You can provide a sorting function to `.sort()`. Try `employeeList.sort(function( a, b ){ return a.age - b.age; });` So no need to create new arrays just to be able to use `.sort()` directly. – Shilly Sep 19 '18 at 13:55
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Luis felipe De jesus Munoz Sep 19 '18 at 14:23

2 Answers2

2

Using sort() method is very easy way to get expected result in a single line of code.

more info

const myTeam = [
  {
    name: "Virat",
    age: 40
  },
    {
    name: "Rohit",
    age: 30
  },
    {
    name: "Bhuvi",
    age: 20
  },
    {
    name: "Raina",
    age: 33
  }
]

const sortedByAge = myTeam.sort((firstEl,secondEl)=> secondEl.age - secondEl.age);

  console.log(sortedByAge);
0

This is what you're looking for: Sort array of objects by string property value in JavaScript

TLDR: You can use the method .sort of an array which can take as a first argument a comparator function. This function takes 2 arguments which will be each object in the for loop.

var employees = [
  {
    age: 28
  },
  {
    age: 18
  },
  {
    age: 35
  }
];
employees.sort(
    function(a, b) {
       return a.age - b.age
    }
);
console.log(employees)

Hope this helps you.

  • I can't figure out why this works in the code snippet and Chrome console, but not in IE console. I would expect this to not work all the time, since `.sort()` expects a number and you return true or false, which is converted to 0 or 1. But if I paste this code into IE console, the array stays in the same order. – Shilly Sep 19 '18 at 14:15
  • Yeah you're right, in fact, sort expects `-1, 0 or 1` but true (1) and false (0) are enough to sort a list. Haven't tried in IE tbh, I'm only using chrome. But isn't that implicit conversion equivalent in every explorer? – Alex Paredes Sep 19 '18 at 14:18
  • In W3Schools doesn't even mention about the 3 possible values, but yes in mozilla's docs [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) – Alex Paredes Sep 19 '18 at 14:20
  • I think IE might not do the conversion automatically and hence, not do the sort, since true is not a number. Hence I always use + and - in sorting functions. Sidenote: it does not have to be -1 0 or 1, any number will suffice according to the spec. – Shilly Sep 19 '18 at 14:22
  • It should be `a.age - b.age` and not `a.age > b.age` – Koushik Chatterjee Sep 19 '18 at 14:28
  • You are both right. I've already edited the answer. Thank you. – Alex Paredes Sep 19 '18 at 14:34