JavaScript

Brian Hernandez
Brian Hernandez
20,173 Points

Trying to create an array of duplicate values from another array, why doesn't my code work?

I am working on this piece of code here where the goal is to create an array of all the values that are duplicated from another array. The resulting array I'd like to have should only enter the duplicated values from the first array once. The catch is I can't use any array functions or methods. This is what I have so far:

var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var tempArr = [];

for (var i = 0; i <= numbers.length; i++) {
    if (tempArr[numbers[i]] === undefined) {
    tempArr[numbers[i]] = 1;
  } else if (results[numbers[i]] === undefined)  {
    results.push(numbers[i]);
  }
}

console.log(results);

I am getting closer to me desired output... but for some reason the results array continues to contain multiple entries of the values that are duplicated in the numbers array. Where am I going wrong here?

2 Answers

Antonio De Rose
Antonio De Rose
16,444 Points

Very good question :)

var array = [24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
    var a = [], prev;

    array.sort();
    for ( var i = 0; i < array.length; i++ ) {
        if ( array[i] !== prev ) {
            a.push(array[i]);
        } 
        prev = array[i];
    }

    console.log(a)
Brian Hernandez
Brian Hernandez
20,173 Points

Thank you but I can't use a method like sort() for this solution.

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 53,855 Points

results[numbers[i]] doesn't correlate to where the number is in the results because the duplicate number is always pushed to the end of the array, not put into the index equal to the number. I think you could count the times you encounter a number by incrementing the spot in tempArr and only pushing the number to results on the 2nd encounter.