I am learning JS, and I have homework. I am asked to transform array into new array where each item is represented by the running count of element appearances.
For example
[1, 2, 1, 1, 3]
becomes
[1, 1, 2, 3, 1]
I wrote a code which works for numbers, but fails tests with strings:
UPDATE: IT works for some numbers, for others does not :/
function duplicates(arr) {
let i, j, newArr = [],
count = 1;
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (i == j) {
continue
}
if (arr[i] === arr[j]) {
newArr.push(count++)
break
}
}
if (j === arr.length) {
newArr.push(1)
}
}
return newArr
}
console.log(duplicates(['a', 'a', 'aa', 'a', 'aa'])) //[ 1, 2, 1, 3, 2] <-- FAILS
console.log(duplicates([1, 2, 1, 2, 3, 1])) //[1, 2, 3, 4, 1, 5] <-- fails
console.log(duplicates([1, 2, 1, 1, 3])) //[ 1, 1, 2, 3, 2, 1 ] <-- MY CODE WORKS
Can you give me a hint? :/
Thank you!