Introduction
A set is a data structure that can store any number of unique values in any order you so wish. Set’s are different from arrays in the sense that they only allow non-repeated, unique values within them.
Thankfully, programming languages tend to have the ability to convert the likes of an array into a set with minimal fuss. However the aim of this article is to device a way that helps us find unique values with Vanilla Javascript and array methods. We will be taking a look at the Set Method and also writing our own Javascript code.
1. The Set Data Structure
The set data structure initialized with a new keyword and then an array is parsed into it as a parameter. If the array has repeating elements it only returns each unique array element from the parsed in Array.
const arr = [1,2,2,3,3,4] //repeated values
const setVal = new Set(arr) //non-repeated, unique values
console.log(setVal)
{1, 2, 3, 4}
2. Using Vanilla JS
We parse the array we want to check as an Argument to the checkItem function.
- An array called newArray is created in the checkItem function.
- We loop through the array parsed in.
- Then we check if the new method does NOT include a value in the array to avoid the repetition.
- If it does not include we push it to the newArray.
- Else we continue the loop without doing anything if it has previously been added to the newArray.
- At the end the new array only adds element that hasn't been previously added.
const checkItem = (itemsArray) => {
let newArray = [];
for (let i = 0; i < itemsArray.length; i++) {
if (!newArray.includes(itemsArray[i])) {
newArray.push(itemsArray[i]);
} else {
continue;
}
}
console.log(newArray);
};
So let us test our function
item=[1,2,2,3,4,4,3,5,6,5,6,7]
checkItem(item)
// This returns
// [1,2,3,4,5,6,7]
//Only unique Values without repetition
As you can see the code is clean and readable, writing your own functions helps improving your problem solving skills, however they can make your code bulky and unnecessarily long.
HAPPY CODING!