Pages

Friday, September 9, 2016

Remove duplicate values from array using Javascript

Filter method in JavaScript can be used to easily remove duplicate values from an array in JavaScript.

Syntax:
array1.filter(callbackfn[, thisArg])

Filter method takes two parameters described as below:
Parameter
Definition
array1
Required. An array object.
callbackfn
Required. A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
thisArg
Optional. An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

Return Value

A new array that contains all the values for which the callback function returns true. If the callback function returns false for all elements of array1, the length of the new array is 0.
This property of filter method can be used to remove duplicates from an array.
Code:
var myArray = ["a","b","c","a"];
var newArray = myArray.filter(function(vale,index,array){
  return array.indexOf(value)==index;
});
alert(newArray);

indexOf(value) returns the first index of value. If it is not equal to the current value, filter returns false, so the value is not included in newArray. Thus, newArray will have unique values only.

No comments:

Post a Comment