Sort JavaScript array of Objects based on one of the object's properties [duplicate]

Asked
Active3 hr before
Viewed126 times

8 Answers

duplicateobjectsobjectjavascriptarray
90%

You can read more about sort here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort,I've got an array of objects, each of which has a property name, a string. I'd like to sort the array by this property. I'd like them sorted in the following way..,Slightly modified from Sorting an array of objects,, @Raynos: No, my function compares the name property of two objects. I have updated it now to account for the order the OP wanted regarding capitalization. – Tim Down Mar 24 '11 at 15:18

There are 2 basic ways:

var arr = [{
   name: "ABC"
}, {
   name: "BAC"
}, {
   name: "abc"
}, {
   name: "bac"
}];

arr.sort(function(a, b) {
   var alc = a.name.toLowerCase(),
      blc = b.name.toLowerCase();
   return alc > blc ? 1 : alc < blc ? -1 : 0;
});

or

arr.sort(function(a, b) {
   return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});

To fix that, you will have to do it like this:

arr.sort(function(a, b) {
   var alc = a.name.toLowerCase(),
      blc = b.name.toLowerCase();
   return alc > blc ? 1 : alc < blc ? -1 : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});

Again here you could choose to use localeCompare instead if you don't want diacritics to affect the sorting like this:

arr.sort(function(a, b) {
   var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
   return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
load more v
88%

let list = [{
      name: "world"
   },
   {
      name: "hello",
   },
];

// This doesn't account for if names are the same between objects
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));

console.log(x);

/*
[
  {
      name: "hello",
  },
  {
      name: "world"
  },
];
*/
load more v
72%

In this tutorial, you have learned how to use the JavaScript Array sort() method to sort arrays of strings, numbers, dates, and objects.,Summary: in this tutorial, you will learn how to use the JavaScript Array sort() method to sort arrays of numbers, string, and objects.,Therefore, to sort employees by hire date, you first have to create a valid Date object from the date string, and then compare two dates, which is the same as comparing two numbers.,This example is similar to the example of sorting an array of numbers in ascending order. The difference is that it compares the salary property of two objects instead.

Consider the following example:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort();
console.log(numbers);
Code language: JavaScript(javascript)
load more v
65%

Arrays of objects can be sorted by comparing the value of one of their properties., The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. ,Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value., The sort method can be conveniently used with function expressions:

// Functionless
sort()

// Arrow function
sort((firstEl, secondEl) => {
   ...
})

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(firstEl, secondEl) {
   ...
})
load more v
75%

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.,To reverse the sorting order, you can invert the return value of the compare function:,In terms of our compareValues function, that means we could write:,We can use the following compare function to sort this array of singers according to their band:

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

const foo = [9, 1, 4, 'zebroid', 'afterdeck'];
foo.sort(); // returns [ 1, 4, 9, 'afterdeck', 'zebroid' ]

const bar = [5, 18, 32, new Set, {
   user: 'Eleanor Roosevelt'
}];
bar.sort(); // returns [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]
load more v
40%

In the above program, the sort() method is used to sort an array by the name property of its object elements.,In the above program, the sort() method is used to sort an array element by the age property.,In this example, you will learn to write a JavaScript program that will sort an array of objects by property values.,The sort() method sorts its elements according to the values returned by a custom sort function (compareName in this case).

Example 1: Sort Array by Property Name

// program to sort array by property name

function compareName(a, b) {

   // converting to uppercase to have case-insensitive comparison
   const name1 = a.name.toUpperCase();
   const name2 = b.name.toUpperCase();

   let comparison = 0;

   if (name1 > name2) {
      comparison = 1;
   } else if (name1 < name2) {
      comparison = -1;
   }
   return comparison;
}

const students = [{
   name: 'Sara',
   age: 24
}, {
   name: 'John',
   age: 24
}, {
   name: 'Jack',
   age: 25
}];

console.log(students.sort(compareName));
load more v
22%

The ES6 object type Set only accepts one copy of each primitive value added to it, so it’s used to find unique values in JavaScript.,However, it’s not obvious how to use Set to find the unique values for a given property among all of the objects contained in a JavaScript array.,There are two ways to use Set to find unique values for an object property:,Let’s say you want to find all the possible values for some property among several JavaScript objects. You can use Set to filter out duplicates by using the .add() (Set.prototype.add()) method to add each value to the Set.

JavaScript Unique Values for a Property in an Array

The ES6 object type Set only accepts one copy of each primitive value added to it, so it’s used to find unique values in JavaScript.

Set
load more v
60%

Set is a new data object introduced in ES6. Because Set only lets you store unique values. When you pass in an array, it will remove any duplicate values.,First, we are creating a new Set by passing an array. Because Set only allows unique values, all duplicates will be removed.,Retrieve the duplicate values, Remove Array Duplicates using ES6 Set

const array = ['🐑', 1, 2, '🐑', '🐑', 3];

// 1: "Set"
[...new Set(array)];

// 2: "Filter"
array.filter((item, index) => array.indexOf(item) === index);

// 3: "Reduce"
array.reduce(
   (unique, item) => (unique.includes(item) ? unique : [...unique, item]),
   [],
);

// RESULT:
// ['🐑', 1, 2, 3];
load more v

Other "duplicate-objects" queries related to "Sort JavaScript array of Objects based on one of the object's properties [duplicate]"