Just JavaScript!!!

Hi Folks!!! This is my first post on Hashnode.

Here are some of JavaScript tricks and functionalities that I encountered during development.

Hope you guys like it.

Remove Duplicates from an Array in JavaScript.

This is the most asked question in a JavaScript interview.

arr = [1,2,1,2,2,1,4,5];
arr.filter((item,index) => arr.indexOf(item) == index); // [1, 2, 4, 5]

The filter() method creates a new array with all the elements that pass the test implemented by the callback() function. In this above example, we are passing current item and its index value to the callback function.

arr.indexOf(item) returns the first index of the item in arr.
For instance, arr[1] will return 0.

For first instance of 1 in arr
item = 1
index = 0.
arr.indexOf(1) will return 0 which is equal to index.

Hence, 1 passes the test and is added to the resultant array.

For 2nd instance of 1 in arr
item = 1
index = 2.
arr.indexOf(1) will return 0 which is not equal to index.

Hence, it will not be added to the resultant array.

Similarly, all the items in an array will undergo the test and the return will be an array with only unique elements.

What will be the output of this code?

Q. [1,2,11,5,26].sort();

In most of the programming languages, the output is fairly simple.

[1,2,5,11,26]

But in JavaScript, we do things differently. So the output will be

[1, 11, 2, 26, 5]

This is because, in JavaScript all array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.
For instance, In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order.

So, How to get the desired result.

Follow me!!!!!

[1,2,11,5,26].sort((a,b) => a-b);
// [1,2,5,11,26]

And Voila!! I have regained my faith in JavaScript...

If we provide our implementation, array elements are sorted according to the return value of our method.

If a and b are two elements being compared, then:

  1. returns less than 0, sort a to an index lower than b (i.e. a comes first).
  2. returns 0, leave a and b unchanged with respect to each other.
  3. returns greater than 0, sort b to an index lower than a (i.e. b comes first).

Note : All null and undefined elements are sorted to the end of the array.

[null,1,undefined,null,2,26,undefined].sort() 
// [1, 11, 2, 26, 5, null, null, undefined, undefined]

That's all folks. Hope this post helps you. I'll be back with more such exciting posts.

Dhonyobaad {Dho-nnyo-bAAd} -- (Thank you in Assamese).