-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortMethod.js
More file actions
41 lines (34 loc) · 810 Bytes
/
SortMethod.js
File metadata and controls
41 lines (34 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Sort Method
// Q.What is sort(); method?
// - It's use to sort element in array.
// NOTE
// - It takes call back function as parameter.
// - If the array has element in numbers form and you use sort method on array. It will treat numbers as string and sort them A to Z. Reason for doing this because of ASCII. Every characters has their own ASCII value which is number.
// SYNTAX
const arr = [1, 5, 3, 4, 2];
// Assenting
arr.sort((a, b) => a - b);
console.log(arr);
// Descending
arr.sort((a, b) => b - a);
console.log(arr);
// Example:
const products = [
{
id: 1,
name: "Phone",
price: 12000,
},
{
id: 2,
name: "Tablet",
price: 60000,
},
{
id: 3,
name: "Laptop",
price: 50000,
},
];
products.sort((a, b) => a.price - b.price);
console.log(products);