Array nested and conditions

i'm learning javascript and trying to solve some exercises. The one I'm into wants me to remove all the duplicates from an array. By far this is my code:

const removeDuplicateds = (arr=undefined)=>{
let count=0;
for (let i=0; i <arr.length ; i++){
    for (let j=1; j<arr.length; j++){
        if (arr[i]=== arr[j]){
            count= count +1;
return console.log(count);


So I wanted to validate this structure by using a counter (the real practice would be to use an arr.splice(j,1) instead of the count=count+1). So it returns 12 times, which means it entered 12 times in the if condition, which is impossible because there should be only 3 times (three 1's in the arr). Any ideas of what's happening? thanks!

3 answers

  • answered 2021-07-27 18:20 saferif

    Despite this solution being not the most effective one, the easiest way to fix the code would be

    let count = 0;
    for (let i = 0; i < arr.length - 1; i++){
        for (let j = i + 1; j < arr.length; j++){
            if (arr[i] === arr[j]){

    Your original code finds too many duplicates because despite pairs (1, 3) and (3, 1) being identical, your code treats them as different.

  • answered 2021-07-27 18:26 Safder

    You also use set.

    let arr = [1,2,3,4,1,1];
    const removeDuplicated = (arr) => {
       const set = new Set(arr)
       return Array.from(set)

  • answered 2021-07-27 18:43 alejandro cabezas unda

    The problem is logic. You are executing the first cycle 6 times, while the second cycle is executed 5 times for each iteration of the previous one. There will be cycles that will enter the if in more than one opportunity try the following:

     const removeDuplicateds = (arr=undefined)=>{
        let result = arr.filter((item,index)=>{
          return arr.indexOf(item) === index;
        return result;

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum