Home > Net >  How to check if particular element in this given array has duplicate?
How to check if particular element in this given array has duplicate?

Time:06-10

I might be overthinking or not even close. How can I iterate on this array to check if an element shows up more than one

var myArr = ["88 99 33", "22 88 99", "23 44 88", "77 99 22"];

for(var x in myArr) {
   var currentNum = myArr[x].split(' ');
   // check currentNum if it appears more than once
}

CodePudding user response:

You can add for example a structure (such as Set) to track whether you have a duplicate:

var myArr = ["88 99 33", "22 88 99", "23 44 88", "77 99 22"];

const numbers = new Set();
const duplicates = new Set();

for (let x in myArr) {
    var arrayItem = myArr[x].split(' ');

    for (var y in arrayItem) {
        const currentNumber = arrayItem[y];

        if (numbers.has(currentNumber)) {
            duplicates.add(currentNumber);
        } else {
            numbers.add(currentNumber);
        }
    }
}

console.log([...duplicates]);

Or use a hash map (i.e., an object) or something:

var myArr = ["88 99 33", "22 88 99", "23 44 88", "77 99 22"];

const numbers = {};

for (let x in myArr) {

  var arrayItem = myArr[x].split(' ');

  for (var y in arrayItem) {

    const currentNumber = arrayItem[y];

    // Track number of appearance of current number
    numbers[currentNumber] = numbers[currentNumber] || 0;
    numbers[currentNumber]  ;

  }
}
// Take only items that appeared more than 1
const duplicates = Object.entries(numbers).filter(([key, value]) => (value > 1)).map(([key,]) => key);

console.log(duplicates);

CodePudding user response:

You can flattern the array and then check is the elem is present more than once.

To check if at least one elemet has duplicates, you can use Array#some

flatArr.some(x => checkDuplicates(x)))

const myArr = ["88 99 33", "22 88 99", "23 44 88", "77 99 22"];
const flatArr = myArr.reduce((acc, curr) => {
  currArray = curr.split(" ")
  if (!acc) return [curArray]
  else return acc.concat(currArray)
}, [])

const checkDuplicates = (elem) => flatArr.filter(item => item === elem).length > 2

console.log(checkDuplicates("88"))
console.log(checkDuplicates("23"))

console.log(flatArr.some(x => checkDuplicates(x)))


Note : If you want to add numbers instead of strings, you can map the array to integer as

const flatArr = myArr.reduce((acc, curr) => {
  currArray = curr.split(" ")
  if (!acc) return [curArray]
  else return acc.concat(currArray)
}, []).map(x => parseInt(x))
  • Related