Home > database >  Checking for "triplicates" strings in JavaScript array
Checking for "triplicates" strings in JavaScript array

Time:06-15



trying to find the best way to check for triplicates values inside an array of strings.
I found many stackoverflow solutions for duplicates values which is not the case in here.
This is the farest i could get with solving this and I am not sure if it is the correct way:

const array = [
    "peace",
    "peace",
    "Vrede",
    "Patz",
    "Salam",
    "paz",
    "Salam",
    "Salam"
  ];

  const findTriplicates = (param) => {
    let counts = {};
    for (let i = 0; i < param.length; i  ) {
      if (counts[param[i]]) {
        counts[param[i]]  = 1;
      } else {
        counts[param[i]] = 1;
      }
    }
    for (let i in counts) {
      if (counts[i] === 3) {
        console.log(i   " exists "   counts[i]   " times.");
      }
    }
  };

  findTriplicates(array); // Salam exists 3 times. 

please don't hesitate to fix my code or to post your solution.
thanks for your support in advance :)
Cheerz!

CodePudding user response:

Your overall idea is good, using Hash Maps (js objects) is the best option for the task.

You can move your "=== 3" check to the first loop and have another object to save triplicates, it will be twice faster.

CodePudding user response:

check this out

  const findTriplicates = (param) => {
  let values = [...new Set(param)];
  let triples = [];

  values.forEach(item=>{
    let counter = 0;
    param.forEach(s=>{
      if(s===item) counter  ;
    })
    if(3==counter) triples.push(item);
  })

  return triples;
  };

CodePudding user response:

There is no correct way to do things like this. You can always optimize or sacrifice performance for readability, but that is up to the developer.

I changed nothing about the functionality in findTriplicates, but the code is very different.

findTriplicates2 works a little different but is by no means superior

const array = [
  "peace",
  "peace",
  "Vrede",
  "Patz",
  "Salam",
  "paz",
  "Salam",
  "Salam"
];

const findTriplicates = (param) => {
  let counts = param.reduce((acc, p) => {
    acc[p] ? acc[p]   : acc[p] = 1
    return acc;
  }, {})
  Object.keys(counts).forEach((key) => counts[key] === 3 &&
    console.log(`${key} exists 3 times.`)
  );
};

findTriplicates(array); // Salam exists 3 times.

const findTriplicates2 = (param) => {
  let triples = [...new Set(param)].reduce((acc, item) => {
    let counter = param.reduce((acc2, s) => {
      if (s === item) acc2  ;
      return acc2;
    }, 0);
    if (3 == counter) acc.push(item);
    return acc;
  }, [])

  triples.forEach((triple) => console.log(`${triple} exists 3 times.`));
};

findTriplicates2(array); // Salam exists 3 times.

  • Related