I have a JS array with strings, for example:
let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e", "e", "e"]
I need to compare for duplicate strings inside the array, and if a duplicate string exists it will be separated like this :
[ ["a", "a", "a"], ["b"], ["c", "c"], ["b", "b", "b"], ["d", "d"], ["e", "e", "e"] ]
I was trying to compare it with for loop, but I don't know how to write code so that array checks its own strings for duplicates, without an already pre-determined string to compare.
let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e", "e", "e"];
let b = [];
let len = a.length;
for (let i = 0; i < len; i++) {
if (b.indexOf(a[i]) !== 1) {
b.push(a[i]);
}
}
console.log(b)
If you start with the zeroth element in the array you get [["a"]] and then if you iterate from the first element and just check whether its the same as the previous element you can determine whether to push to the existing last array, or start a new one.
So use slice to get the array except the zeroth element and forEach to accumulate your new array:
let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e", "e", "e"]
var result = [[a[0]]]
a.slice(1).forEach( (e,i) => {
if(e == a[i]) {
result[result.length-1].push(e);
} else{
result.push([e]);
}
});
console.log(result)
If you wanted to keep track of a count also, thats fairly similar
let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e", "e", "e"]
var result = [{count:1, char:a[0]}]
a.slice(1).forEach( (e,i) => {
if(e == a[i]) {
result[result.length-1].count++;
} else{
result.push({count:1, char: e});
}
});
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With