Javascript Get Unique Values from an Array
Hello devs, today I'll show you how to get unique values from an array in a pure javascript way. Sometimes we require it to the filter the array and pass the only unique values to our backend. So, in that case today's tutorial will be helpful. So, let's get started.
Get the Unique Values from An Array Elements
For getting the unique values from an array we'll use the filter() method of array. Let's see the below code snippet.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Unique Values form Array - shouts.dev</title>
</head>
<body>
<script type="text/javascript">
var stacks = ["PHP","Python","Javascript","PHP"];
var uniqueStacks = stacks.filter(function(item, i, sites) {
return i == sites.indexOf(item);
});
console.log(uniqueStacks);
</script>
</body>
</html>
Which will produce the below output.
Here what actually we do is, firstly we'll declare an array element, and then we'll use an array method called filter() which helps us to remove the duplicate values. For more info about filter() method, see here.
That's it for today. Hope you've enjoyed this tutorial. Catch me in the comment section if anything goes wrong. Thanks for reading.