Javascript Array Tricks

JavaScript, at its base, is a very simple language. Due to burst of Js framework usage, in which many new developers jumps right into, there are very useful basic JavaScript techniques and tricks which many people are unaware of.

Today I want share some tricks with Javascript Arrays, which many developers are not using.

Cloning Array

Sorting

vara=[1,4,2,3];console.log(a.reverse());//=> [3,2,4,1]console.log(a.sort());//=> [1,2,3,4]// Sort is more powerful than we think// sort descendingconsole.log(a.sort(function(a,b){return(b-a);}));//=> [4,3,2,1]

Array.sort() accepts an optional parameter in the form of a function, which accepts two paramameters. The array elements can sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value.

The three possible return numbers are:

Less than 0: Sort “a” to be a lower index than “b”

Zero: “a” and “b” should be considered equal, and no sorting performed.