3

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)

0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use .reduce() method to get the desired output like below:

const data = ['a', 'a', 'a', 'b', 'c', 'c', 'b', 'b', 'b', 'd', 'd', 'e', 'e', 'e'];

const result = data.reduce(
  (r, c, i, a) => (
    c != a[i - 1] ? r.push([c]): r[r.length - 1].push(c), r
  ), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

.map() and .fill() are unnecessary if you store the characters in the object instead of just a number...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.