-1

Here is the prompt: Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Get all unique values in a JavaScript array (remove duplicates)

I used variances of the above questions/answers and tried to amend it for what I am looking for- the count of how many elements are found more than once

var arr = 'Indivisibilities';
var sorted_arr = arr.toLowerCase().split('').sort();

let count = 0;

let duplicateCount = (parm1) => {
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        count ++;
    }
} return count;
}

duplicateCount(arr);

Count returns 7, what is expected is 2. Also, I would really like to avoid using a for loop. I'm hoping this can be done with .forEach or something method. ** I'm still pretty knew to code so please try not to do any one liners :) I appreciate the efficiency, but I'm still trying to understand the logic

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Vanessa
  • 43
  • 4
  • 1
    Why do you expect 2? *count* is incremented once for each duplicate, there are 6 duplicate "i" and one duplicate "s". If you want to count how many characters are duplicated, you'll have to keep track of the ones you've seen so they don't get double (or sextuple) counted. :-) – RobG Aug 23 '19 at 02:12
  • I'm not seeing an answer to `@RobG`'s question. Duplicates of what, every character? There are more than 2. – StackSlave Aug 23 '19 at 02:26
  • @RobG yes, you are correct, the way the code is written, count will give return 2. It's why I'm lost because I'm not sure how to count the occurance just once, not through every repeated element. Do I throw it in another loop to check that they haven't been counted? – Vanessa Aug 23 '19 at 02:34

1 Answers1

2

You can use reduce and filter

  • Change string to lowercase
  • Split string by ''
  • Use each element as key, if it is already present increase it's count by 1 else set it to 1
  • Filter values which are greater than 1 to see duplicates
  • Get length of filtered array

var str = 'Indivisibilities';

let duplicateCount = (str) => {
  let dups = str.toLowerCase().split('').reduce((op,inp)=>{
    op[inp] = op[inp] || 0
    op[inp]++
    return op
  },{})
  return Object.values(dups).filter(v=>v>1).length
}

console.log(duplicateCount(str));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60