Javascript Arrays - Find Duplicates

javascript

Solution

One way of doing this (and it's not the only way) is by checking for existing elements in the array. Take a look at JavaScript's lastIndexOf function:

http://www.w3schools.com/jsref/jsref_lastindexof_array.asp

It will return -1 if the object does not exist in your array, and if it exists, will return an index of a later position than you are in. So you can use an if statement in your loop that checks whether or not there is another index containing your number, and add it in to your results array IF AND ONLY IF the index you get back != the index you are currently on (if they equal, this means that there is only one of that element in the list).

If you need more help, comment here and I can type some code in!

Good luck!

Problem

Here is my question... Given an array populated with numbers as a function parameter, produce a resulting array which contains any duplicates number from the array. For example, given the array [ 1, 2, 4, 4, 3, 3, 1, 5, 3 ] it should return [1, 4, 3]. For extra bonus points return a sorted array. I am starting out with Javascript - I know the language however, using it in the correct way ( as one should ) I'm still getting to grips with. My pseudo code for this would be to: Create an array with the numbers above `var numbers = [1, 2, 4, 4, 3, 3, 1, 5, 3];` Then create an empty array named "result" `var result = [];` Create a for loop that goes through the var numbers to check for duplicates which will then populate the empty array "result" with the duplicates ``` for (var i = 0;i < numbers.length; i++) { //This is where I'm stuck... } ``` I'm not sure what to do within the for loop to populate the var result and to throw in to the mix... The given array has to be a function parameter which makes sense so you can change the numbers in one place. Any feedback on my thought process on this so far is greatly appreciated but ultimately I am wanting to learn how to achieve this. Here is a JSFiddle of my progress so far... http://jsfiddle.net/fbauW/

Original source

Related problems