Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to return a certain value from an array

I am trying to create a function that return an integer that only appears once in an array. For example:

var arr = [1 , 1, 2, 3, 3,];

The function would return the value 2 as it only appears once.

This is what I have so far but I feel I am very off

function singleInteger(arr){
          for(var i = 0; i < arr.length; i+=1)
                 if(arr[i].indexOf() > 1){
                        return arr[i];
                         }
}

I dont have the time yet to write your code...but this should help you http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array

Do you have a reason to do this? Would you like it to return all values that only appear once - or will your arrays each only have one number that appears just once?

Hey Matt,

I want the function to return all values in an array that only appear once.

1 Answer

Hi Michael,

Here is a function that will find all values that occur just once in an array.

function findSingles (arr) {
  return arr.reduce(function(singles, curValue, curIndex) {
    var curIndexOmittedArray = arr.slice(0, curIndex).concat(arr.slice(curIndex + 1));
    if (curIndexOmittedArray.indexOf(curValue) === -1) {
      singles.push(curValue);
    }
    return singles;
  }, []) 
}

Here is it working on CodePen: http://codepen.io/mq9_reaper/pen/grMLWa?editors=0010