3

You are given a non-empty list of integers. For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and result will be [1, 3, 1, 3].

function nonUniqueElements(data) { var array = []; for (var i = 0; i < data.length; i++) { while (i >= 2) { array.push(i); } return data; } } 
6
  • All you do is check to see if i is greater than t2o, it does nothing to check to see if the number exists. Commented Nov 10, 2016 at 22:20
  • would you be able to give me any hint without providing a solution please? Commented Nov 10, 2016 at 22:22
  • loop over the array and see if the element exists more than once. Commented Nov 10, 2016 at 22:24
  • I thought im already looping through an array Commented Nov 10, 2016 at 22:27
  • Hmm, seems I read this question wrong - for some reason, I thought it was "remove the duplicates entries, including all the duplications they have" but it's actually the opposite - "leave only the duplicates". In which case, the Remove Duplicates question does work, simply do the opposite. Commented Nov 10, 2016 at 22:31

2 Answers 2

1

My solution:

  1. First loop over the array to count how much each number appears in the array
    by using map. Total time is O(n)
  2. And than loop again over the array and push to the new array the number, only if the current number appears more than 1 in the map. Total time is O(n).

     function nonUniqueElements(data) { //first loop over the array and find all duplications //create a map with all the numbers //the key will be the number, //and the value will be how much each number appears in the array var map = {}; for (var i=0; i < data.length; i++){ if (map[data[i]] == undefined){ //the number does not exist in the map, than push to map map[data[i]] = 0; } else {//the number alredy exists //increase the counter map[data[i]] = map[data[i]] +1; } } //now, loop over the array once again var nonUniqueArray = []; for (var i=0; i < data.length; i++){ //if the value of the current element is more than 1 if (map[data[i]] > 0){ //push to the new nonUniqueArray nonUniqueArray.push(data[i]); } } //return the non unique array return nonUniqueArray; } 

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

0

Use nested for loops that traverse the same array, in this case data.

First check if the index of each loop is the same. If it is do nothing. If they are not the same check the values. If the values are equal push to the array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.