RSS

Monthly Archives: August 2018

Javascript Find Unique Value in Array

Given:

var findUniq = ["f", "3", 3, "t", "f", "A"]

Find only unique value.

Solution 1 – Javascript ECMA Script 5
Check if index of the value is the first occurrence.

var uniq = findUniq.filter(function(value, index, array) {
    return array.indexOf(value) === index;
});

Solution 2 – Javascript ECMA Script 6
Short hand version of Solution 1.

let uniq = findUniq.filter((v, i, a) => a.indexOf(v) ==== i);

Solution 3 – Javascript ECMA Script 6
Using Set data type, which only allow unique value.

let uniq = [...new Set(findUniq)];

Credit:
https://stackoverflow.com/a/14438954/631631

Advertisements
 
Leave a comment

Posted by on August 11, 2018 in General

 

Tags: , , , , ,

 
%d bloggers like this: