As per the title, in one of the interview I got the above problem to solve, but i confused to get the answer. Can any one give me the solution please.
Thanks in Advance!
I am expecting solution as per the requirement without using any built in methods available in JavaScript.
2
Answers
You would use a for loop.
The
removeDuplicates
function takes an array as input and creates a new array (uniqueArray
) to store the unique elements. It then iterates through each element in the input array using a for loop.For each element in the input array, it checks whether that element is already present in the
uniqueArray
using theindexOf
method. If the element is not found (i.e., indexOf returns -1), it means the element is unique, and it is added to the uniqueArray using thepush
method.See below example:
You can remove duplicate elements from an array in JavaScript without using built-in array methods by creating a new array and iterating through the original array. Here’s one way to achieve this:
In the above example, the removeDuplicates function iterates through the original array (arr) and checks whether each element is already present in the uniqueArray using the indexOf method. If the element is not found in uniqueArray (i.e., indexOf returns -1), it is added to the uniqueArray. This way, duplicates are not included in the new array.