You are currently viewing Sorting an array of Objects by String Property Value
sorting-an-array-of-objects-by-string-property-value

Sorting an array of Objects by String Property Value

Sorting of an array in Javascript

This is an example array .

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

The code defines an array named objs which contains three objects. Each object has two properties: first_nom and last_nom. The properties have string values that represent first and last names, respectively.

Now we have to Sorting an array of Objects by String Property Value with different methods.

Method 1 :

function compare( a, b ) {
  if ( a.last_nom < b.last_nom ){
    return -1;
  }
  if ( a.last_nom > b.last_nom ){
    return 1;
  }
  return 0;
}

objs.sort( compare );

Explanation :

The code defines a function compare(a, b) which compares two objects a and b based on the value of their last_nom property.

  • If the last_nom property of a is less than b, it returns -1.
  • If the last_nom property of a is greater than b, it returns 1.
  • If they are equal, it returns 0.

The sort function is called on the objs array and sorts its elements in place based on the return value of the compare function. After this function is called, the objs array will be sorted in ascending order based on the last_nom property of each object.

 

Method 2 :

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

Explanation :

The code sorts the objs array in place based on the value of the last_nom property of each object, in ascending order.

The sort method is called on the objs array and takes an anonymous arrow function as its argument. The arrow function takes two arguments, a and b, which represent two objects in the array.

The function uses a ternary operator to return 1, -1, or 0 based on the comparison of a.last_nom and b.last_nom.

  • If a.last_nom is greater than b.last_nom, the function returns 1.
  • If b.last_nom is greater than a.last_nom, the function returns -1.
  • If they are equal, the function returns 0.

The returned value is used by the sort method to sort the objs array in ascending order based on the value of the last_nom property.

Method 3 :

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        /* next line works with strings and numbers, 
         * and you may want to customize it to your needs
         */
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

Explanation :

The code defines a function dynamicSort(property) which returns a function that can be used to sort an array of objects based on the specified property argument.

  • If the first character of property is -, it sets the sortOrder variable to -1 and removes the - from property. This means the sorting will be in descending order.
  • If the first character is not -, sortOrder is set to 1, indicating an ascending sort.

The returned function takes two arguments, a and b, which represent two objects in the array to be sorted.

The function performs a comparison between the values of a[property] and b[property], and returns a value of -1, 1, or 0 based on the comparison.

  • If a[property] is less than b[property], the function returns -1 * sortOrder.
  • If a[property] is greater than b[property], the function returns 1 * sortOrder.
  • If they are equal, the function returns 0.

The returned function can be used to sort an array of objects based on the value of the specified property argument, either in ascending or descending order.

Example Array of object is as follows

var People = [
    {Name: "Name", Surname: "Surname"},
    {Name:"AAA", Surname:"ZZZ"},
    {Name: "Name", Surname: "AAA"}
];

The code defines a variable People which is an array of three objects. Each object represents a person and has two properties: Name and Surname. The first object has the property values “Name” and “Surname”, the second object has “AAA” and “ZZZ”, and the third object has “Name” and “AAA”.

And we use above code as follows

People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));

Explanation :

The code sorts the People array three times, each time using a different property value passed to the dynamicSort function.

  1. People.sort(dynamicSort("Name")) sorts the People array in ascending order based on the value of the Name property of each object.
  2. People.sort(dynamicSort("Surname")) sorts the People array in ascending order based on the value of the Surname property of each object.
  3. People.sort(dynamicSort("-Surname")) sorts the People array in descending order based on the value of the Surname property of each object.

After each call to the sort method, the People array will be rearranged in place based on the specified property values and the return value of the dynamicSort function.

 

Method 4 :

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];


// Define a couple of sorting callback functions, one with hardcoded sort key and the other with an argument sort key
const sorter1 = (a, b) => a.last_nom.toLowerCase() > b.last_nom.toLowerCase() ? 1 : -1;
const sorter2 = (sortBy) => (a, b) => a[sortBy].toLowerCase() > b[sortBy].toLowerCase() ? 1 : -1;

objs.sort(sorter1);
console.log("Using sorter1 - Hardcoded sort property last_name", objs);

objs.sort(sorter2('first_nom'));
console.log("Using sorter2 - passed param sortBy='first_nom'", objs);

objs.sort(sorter2('last_nom'));
console.log("Using sorter2 - passed param sortBy='last_nom'", objs);

Explanation :

The code defines an array objs with three objects, each with two properties: first_nom and last_nom.

Two sorting callback functions sorter1 and sorter2 are defined. sorter1 has hardcoded the last_nom property to be used for sorting and sorter2 accepts a parameter sortBy which specifies the property to be used for sorting.

The code sorts the objs array three times using the sort method and passing each time a different sorting callback function.

  1. objs.sort(sorter1); sorts the objs array in ascending order based on the value of the last_nom property of each object.
  2. objs.sort(sorter2('first_nom')); sorts the objs array in ascending order based on the value of the first_nom property of each object.
  3. objs.sort(sorter2('last_nom')); sorts the objs array in ascending order based on the value of the last_nom property of each object.

After each call to the sort method, the objs array will be rearranged in place based on the specified property values and the return value of the corresponding sorting callback function. The sorted arrays are logged to the console after each sort.

Console log value is as

Using sorter1 - Hardcoded sort property last_name [
  {
    "first_nom": "Pig",
    "last_nom": "Bodine"
  },
  {
    "first_nom": "Lazslo",
    "last_nom": "Jamf"
  },
  {
    "first_nom": "Pirate",
    "last_nom": "Prentice"
  }
]
Using sorter2 - passed param sortBy='first_nom' [
  {
    "first_nom": "Lazslo",
    "last_nom": "Jamf"
  },
  {
    "first_nom": "Pig",
    "last_nom": "Bodine"
  },
  {
    "first_nom": "Pirate",
    "last_nom": "Prentice"
  }
]
Using sorter2 - passed param sortBy='last_nom' [
  {
    "first_nom": "Pig",
    "last_nom": "Bodine"
  },
  {
    "first_nom": "Lazslo",
    "last_nom": "Jamf"
  },
  {
    "first_nom": "Pirate",
    "last_nom": "Prentice"
  }
]

Method 5 :

obj.sort(function(a,b){
  if(a.last_nom< b.last_nom) return -1;
  if(a.last_nom >b.last_nom) return 1;
  if(a.first_nom< b.first_nom) return -1;
  if(a.first_nom >b.first_nom) return 1;
  return 0;
});

If you have duplicate last names you might sort those by first name

This JavaScript code sorts an array of objects obj based on the values of the properties last_nom and first_nom. The sort() method takes a comparison function as an argument and sorts the array in place, meaning it modifies the original array.

The comparison function compares two objects a and b and returns a value indicating their order:

  • If a.last_nom is less than b.last_nom, it returns -1, meaning a should come before b in the sorted array.
  • If a.last_nom is greater than b.last_nom, it returns 1, meaning b should come before a in the sorted array.
  • If a.last_nom is equal to b.last_nom, it then compares first_nom.
  • If a.first_nom is less than b.first_nom, it returns -1.
  • If a.first_nom is greater than b.first_nom, it returns 1.
  • If a.first_nom is equal to b.first_nom, it returns 0, indicating that the order doesn’t matter and the elements are considered equal.

Method 6 ;

A simple function that sorts an array of object by a property:

function sortArray(array, property, direction) {
    direction = direction || 1;
    array.sort(function compare(a, b) {
        let comparison = 0;
        if (a[property] > b[property]) {
            comparison = 1 * direction;
        } else if (a[property] < b[property]) {
            comparison = -1 * direction;
        }
        return comparison;
    });
    return array; // Chainable
}

This is a JavaScript function for sorting arrays of objects based on a specified property. The function takes an array, a property to sort on, and an optional sort direction (ascending or descending). If no sort direction is specified, it defaults to ascending (1). The function uses the Array.sort() method, with a compare function that compares the values of the specified property of two objects. The comparison results in either 1 (for a > b), -1 (for a < b), or 0 (for a = b). The sort direction is applied to the comparison result to determine the final sort order. The function returns the sorted array.

Usage:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc

This code uses the sortArray function to sort the objs array of objects first in ascending order based on the “last_nom” property and then in descending order based on the same property.

The result of sortArray(objs, "last_nom") will be:

[     { first_nom: 'Pirate', last_nom: 'Prentice' },    { first_nom: 'Lazslo', last_nom: 'Jamf'     },    { first_nom: 'Pig',    last_nom: 'Bodine'   }];
[     { first_nom: 'Pig',    last_nom: 'Bodine'   },    { first_nom: 'Lazslo', last_nom: 'Jamf'     },    { first_nom: 'Pirate', last_nom: 'Prentice' }];

 

Print Friendly, PDF & Email

Leave a Reply