Js Filter And Sort

Filter – High order function used to filter any array with the help of the callback function it uses same argument as map only difference is the return type is either true or false.

It return type is true value is kept in the array if false value is removed.

Lets have an example to understand its implementation.

let arr1 = [6, 1, 3, 2, 8, 1, 7, 5, 9 ,9];

As you can see arr1 is an array with values 1-9 with non unique values.

to get values greater than 4

a.filter(x => x>4)
// output [6, 8, 7, 5, 9, 9]

Sort – High order function used to sort values in asc or desc order.

Lets have an example to understand its implementation.

let arr2 = [6, 1, 3, 2, 8, 1, 7, 5, 9 ,9];

As you can see arr2 is an array with values 1-9 with non unique values.

to get values in asc order

arr2 = arr2.sort()
//output [1, 1, 2, 3, 5, 6, 7, 8, 9, 9]

to get values in desc order

arr2 = arr2.sort( (a, b) => b - a );
//output [9, 9, 8, 7, 6, 5, 3, 2, 1, 1]

for string

to get values in asc order

let arr3 = ['a', 'b', '25', '100'];
arr3 = arr3.sort( (a, b) => a < b ? -1 : 1 );
// output ["100", "25", "a", "b"]

as you can see 100 is shown smaller than 25 as sort compares 1 to 2 and 1 is clearly smaller than 2 and rest are arranged in alphabetical order as in a Dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *