1const books = [
2 {id: 1, name: 'The Lord of the Rings'},
3 {id: 2, name: 'A Tale of Two Cities'},
4 {id: 3, name: 'Don Quixote'},
5 {id: 4, name: 'The Hobbit'}
6]
7
8books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
1const list = [
2 { color: 'white', size: 'XXL' },
3 { color: 'red', size: 'XL' },
4 { color: 'black', size: 'M' }
5]
6
7list.sort((a, b) => (a.color > b.color) ? 1 : -1)
1var array = [
2 {name: "John", age: 34},
3 {name: "Peter", age: 54},
4 {name: "Jake", age: 25}
5];
6
7array.sort(function(a, b) {
8 return a.age - b.age;
9}); // Sort youngest first
1const list = [
2 { color: 'white', size: 'XXL' },
3 { color: 'red', size: 'XL' },
4 { color: 'black', size: 'M' }
5]
6
7var sortedArray = list.sort((a, b) => (a.color > b.color) ? 1 : -1)
8
9// Result:
10//sortedArray:
11//{ color: 'black', size: 'M' }
12//{ color: 'red', size: 'XL' }
13//{ color: 'white', size: 'XXL' }
1const books = [
2 {id: 1, name: 'The Lord of the Rings'},
3 {id: 2, name: 'A Tale of Two Cities'},
4 {id: 3, name: 'Don Quixote'},
5 {id: 4, name: 'The Hobbit'}
6]
7
8compareObjects(object1, object2, key) {
9 const obj1 = object1[key].toUpperCase()
10 const obj2 = object2[key].toUpperCase()
11
12 if (obj1 < obj2) {
13 return -1
14 }
15 if (obj1 > obj2) {
16 return 1
17 }
18 return 0
19}
20
21books.sort((book1, book2) => {
22 return compareObjects(book1, book2, 'name')
23})
24
25// Result:
26// {id: 2, name: 'A Tale of Two Cities'}
27// {id: 3, name: 'Don Quixote'}
28// {id: 4, name: 'The Hobbit'}
29// {id: 1, name: 'The Lord of the Rings'}
1// Handles mix-cased strings and numbers with option for setting order
2const sortObjectArray = ({ arr, field, order = 'desc' }) => {
3 arr.sort(function(a, b) {
4 const fieldA = typeof a[field] === 'string' ? a[field].toLowerCase() : a[field]
5 const fieldB = typeof b[field] === 'string' ? b[field].toLowerCase() : b[field]
6
7 let result
8 if (order === 'desc') {
9 result = fieldA > fieldB ? 1 : -1
10 } else {
11 result = fieldA < fieldB ? 1 : -1
12 }
13 return result
14 })
15 return arr
16}
17
18let arr = [
19 {name: "John", age: 34},
20 {name: "Peter", age: 54},
21 {name: "jake", age: 25}
22]
23
24let arr2 = sortObjectArray({ arr, field: 'name'})
25console.log(arr2)
26/*
27[
28{ age: 25, name: "jake"},
29{ age: 34, name: "John" },
30{ age: 54, name: "Peter" }
31]
32*/
33
34let arr3 = sortObjectArray({ arr, field: 'age', order: 'asc' })
35console.log(arr3)
36/*
37[
38{ age: 54, name: "Peter" },
39{ age: 34, name: "John" },
40{ age: 25, name: "jake"}
41]
42*/