Alex
Alex

Reputation: 35

JS Find indices of duplicate values in array if there are more than two duplicates

I'm creating coordinate plane Three in a row game so I have to find out if there are three numbers of the same value in the array BUT WITHOUT sorting array because the array represents the x-coordinates of the points added to the coordinate plane during the game... For example, let's say that I've added 6 points to the coordinate plane with x-coordinates stored in next array:

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

I need the loop that will count only the occurrences of the value 2 because the number 2 occurs 3 times in array, so the output should be a new array (for example array named indices) with the exact indices of nmb 2 occurrences in arr...

indices = [0,1,3]

The loop should therefor "reset" when comes to the end of the arr if the number of occurrences of some value is less than 3...

I've tried the next code, but it doesn't work like I've described above because it counts the number of occurrences of the number 3 as well... so, it won't "reset" if value count is less than 2...

var arr = [2,2,3,2,7,3];
var index = [];
var count = 0;
var current;
for(var i = 0;i<arr.length;i++){
    current = arr[i];
    //-------------------------------
    for(var j=i+1;j<arr.length;j++){
        if(arr[j]===current){
            count++;
            index.push(j);
            //+++++++++++
            if(j===arr.length-1){
                if(count<2){
                    count = 0;
                    index = [];
                    i++;
                }
                else{
                    index.unshift(i);
                    break;
                }
            }
            //+++++++++++
        }
    }
    //-------------------------------
}
alert(index);

Thanks for any help or advice...

Aleksandra

Upvotes: 2

Views: 16124

Answers (8)

Uday Shankar
Uday Shankar

Reputation: 458

You can get the desired result using filter() or reduce().

Approach using filter():

const arr = [2,2,3,2,7,3];
var keys = [];

var filtered = arr.filter((e, i) => {
  if (e === 2) {
    keys.push(i);
  }
});

console.log(keys);

Approach using reduce():

const arr = [2,2,3,2,7,3];

const indexes = arr.reduce((r, n, i) => {
  n === 2 && r.push(i);
  return r;
}, []);

console.log(indexes);

One can wrap this logic inside a function to get the desired result without need of repeating the code at different places.

Upvotes: 0

Samaneh Mobasser
Samaneh Mobasser

Reputation: 1

Find all duplicate elements in an array:

const array = [4,2,34,4,1,12,1,4];
const newArray = [];

for (let i = 0 ; i < array.length; i++) {
    if (array.indexOf(array[i]) !== i && newArray.indexOf(array[i]) === -1) {
        newArray.push(array[i]);
    }
}
console.log(newArray);

Upvotes: 0

Jorawar Singh
Jorawar Singh

Reputation: 7621

I would do like this way:

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

var indices = [];

arr.filter(function(yourArray, index) {
 if(yourArray == 2){
   indices.push(index)
 }
});
console.log(indices)

If you print the indices, it will contain this output:

[0,1,3]

If you want to check that there are more than two duplicates, you can do it this way:

var arr = [2,2,3,2,7,3];
var counts = arr.filter(function(yourArr,index, self){
  return !self.indexOf(yourArr) 
});

var indices = [];

arr.filter(function(yourArr, index, self){
  if(yourArr == 2 && counts.length > 2){
   indices.push(index)
 }
})
console.log(indices)

Upvotes: 8

Mehmet Filiz
Mehmet Filiz

Reputation: 720

this function covers all my duplicate finding needs


function findAllDuplicatesInListOfObjects(list, prop) {
  const duplicates = [];
  const len = list.length;
  for (let i = 0; i < len - 1; i++) {
    for (let j = i + 1; j < len; j++) {
      if (list[i][prop] === list[j][prop]) {
        const index = duplicates.findIndex(e => e[prop] === list[i][prop]);
        if (index != -1) {
          if (!duplicates[index].indexes.includes(j)) {
            duplicates[index].indexes.push(j);
          }
        } else {
          duplicates.push({
            indexes: [i, j],
            [prop]: list[i][prop],
          });
        }
      }
    }
  }
  return duplicates;
}

const users = [
  { name: 'user', pushtoken: 'aa' },
  { name: 'user', pushtoken: 'bb' },
  { name: 'user', pushtoken: 'cc' },
  { name: 'user', pushtoken: 'dd' },
  { name: 'user', pushtoken: 'ee' },
  { name: 'user', pushtoken: 'cc' },
  { name: 'user', pushtoken: 'bb' },
  { name: 'user', pushtoken: 'cc' },
  { name: 'user', pushtoken: 'aa' },
  { name: 'user', pushtoken: 'bb' },
  { name: 'user', pushtoken: 'cc' },
];

const duplicates = findAllDuplicatesInListOfObjects(users, 'pushtoken');

console.log(duplicates);

results

[
  { indexes: [ 0, 8 ], pushtoken: 'aa' },
  { indexes: [ 1, 6, 9 ], pushtoken: 'bb' },
  { indexes: [ 2, 5, 7, 10 ], pushtoken: 'cc' }
]

Upvotes: 0

KOOKY
KOOKY

Reputation: 11

If you want something like this:

Input:
array = ["same", "same", "duo", "same", "duo", "lonely", "same"];

Output:
indices = {
    "same": [0, 1, 3, 6],
    "duo": [2, 4],
    "lonely": [5]
}

Try this code

let array = ["same", "same", "duo", "same", "duo", "lonely", "same"];
let indices = {};

for (let i = 0; i < array.length; i++) {
    if (!indices[array[i]]) {
        indices[array[i]] = [];
    }
    indices[array[i]].push(i);
}

console.log(indices);

Upvotes: 1

here is a function that return an array of duplicate element's indexes

let letters = ["b","a","f","g","h","v","s","e","a","t","h","d","z","r", "a", "f" ]
function duplicateIndexes(arr, el){

    duplicate = [];
    for (let i = 0; i < arr.length; i++){
        if (arr[i] == el){
            duplicate.push(i)
        } 
    }
    return duplicate
}
let d = duplicateIndexes(letters, "a")
console.log(d)

Upvotes: 1

Ji_in_coding
Ji_in_coding

Reputation: 1701

this is my solution.

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

var dictionary = {};
for(var i=0;i<arr.length;i++){
  if(dictionary[arr[i]]){
    dictionary[arr[i]]++;
  }else{
    dictionary[arr[i]] = 1;
  }
}

for(var num in dictionary){
  if(dictionary[num] == 3){
    alert(num);
  }
}

Upvotes: 1

zb&#39;
zb&#39;

Reputation: 8059

Yes, using some logic...

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

function showDupPos(arr, mindups) {
  mindups = mindups || 2;
  var result = [];
  var positions = {};
  // collect all positions
  arr.forEach(function(value, pos) {
    positions[value] = positions[value] || [];
    positions[value].push(pos);
  });
  //check how much of same value in string
  Object.keys(positions).forEach(function(value) {
    var posArray = positions[value];
    if (posArray.length > mindups) {
      result = result.concat(posArray);
    }
  });
  return result.sort();
}
console.log(showDupPos(arr));

Upvotes: 3

Related Questions