CodingTrapper
CodingTrapper

Reputation: 11

counting duplicates from a passed in string

so i had this problem on codewars, where i have to find same letters in a passed in string and shall return the letters that are twice or more often inside that string. Here is my attempt which threw out an error:

function duplicateCount(text){
  text.split('')
  for(var i = 0, i < text.length, i++) {
    for(var j = 1, j < text.length + 1, j++)
      if(text[j] = text[i]) {
        return text[i]
      }
    else return
  }
  //...
}

i have very little expierience so dont be to harsh lmao

Upvotes: 1

Views: 1614

Answers (5)

Baby Aneesha Koduri
Baby Aneesha Koduri

Reputation: 1

const value = 'blockquotes';
let arr = value.split('');
let res = {};
for(let i = 0; i < arr.length ; i++){
if(Object.keys(res).includes(arr[i])){
res[arr[i]] = res[arr[i]]+1;
}
else{
res[arr[i]] = 1;
}
}
console.log(res);

Upvotes: -2

sofa_maniac
sofa_maniac

Reputation: 1657

You can try converting the string array to a set. Since sets can't have duplicates, you will get the difference in size. Therefore, the count.

const countDuplicates = (str) => {
    const arr = str.split(''); 
    const arrSet = new Set(arr);
    return arr.length - arrSet.size 
}

console.log(countDuplicates('abcdac')

Output: 2

Edit: I missed the part where you asked about returning the duplicate characters. For that:

const getDuplicateChars = (str) => { 

const arr = str.split('');
const duplicateChars = [];
const sortedArr = [...arr].sort();

sortedArr.forEach((elem, index) => {
    if(sortedArr[index+1] === elem) {
        duplicateChars.push(elem);
    }
});
return duplicateChars;
}

let duplicateChars = getDuplicateChars('abcdac');

Upvotes: 1

Youcef Ali
Youcef Ali

Reputation: 309

you can try this :

let duplicate=text.split('').filter((item, index) => text.split('').indexOf(item) != index)

Upvotes: 0

Sagar V
Sagar V

Reputation: 12478

Unlike the title, your question body and the code says you want letters that appear more than once.

Your method have some issues.

text.split('') won't alter original array. It simply returns an array.

use ; instead of , in for loop.

Here's an alternative method in ES6.

  1. convert string to lowercase to match all characters regardless of case. Remove .toLowerCase() if you want to match case.
  2. Split the string to array
  3. Use filter with conditition (x,y) => str.indexOf(x) != y) to get duplicate elements.
  4. Since the resulting array may have duplicate elements and you want only repeating elements, we need to remove duplicates form array.
  5. Use filter with conditition (x,y) => arr.indexOf(x) == y) to get non duplicate elements.
  6. Here, I used IIFE to pass the first filtered array to second filter function and return it directly.
  7. You can use Set instead of second filter, if you want.

duplicateFind = (str) => {
  str = str.toLowerCase().split('');
  return ((arr) => arr.filter((x, y) => arr.indexOf(x) == y))(str.filter((x, y) => str.indexOf(x) != y))
}
console.log("Letters appearing more than once in string 'Hello there'");
console.log(duplicateFind("Hello there"));

Upvotes: 0

KooiInc
KooiInc

Reputation: 122936

Here a two ways to determine which characters of a string occur twice or more in that string.

Learn more:

const str = "I_am_a_string_with_probably_duplicate_characters";
console.log(JSON.stringify(duplicateCount(str)));
console.log(duplicateCountLoop(str).join("; "));

// using a reducer/filter
function duplicateCount(text){
  // determine the frequencies of each character in the string
  const charFrequencies = text.split('')
    .reduce( (acc, chr) => ({...acc, [chr]: (acc[chr] || 0) + 1}), {});
  // filter the result for character with more than 1 ocurrences  
  return Object.fromEntries(Object.entries(charFrequencies)
    .filter( ([key, value]) => value > 1 )
  );
}

// in a loop
function duplicateCountLoop(text){
  // determine the frequencies of each character in the string
  const textIterable = text.split('');
  let characterFrequencies = {};
  for (let chr of textIterable) {
    characterFrequencies[chr] = (characterFrequencies[chr] || 0) + 1;
  }
  let result = [];
  for (freq in characterFrequencies) {
    if (characterFrequencies[freq] > 1) {
      result.push(`${freq}: ${characterFrequencies[freq]}`);
    }
  }
  return result;
}

Upvotes: 0

Related Questions