1

I'm pretty new to coding and I'm practicing some array manipulation. Basically, I'm trying to organize this array:

const sequence = ["abc", "abcd", "bca", "bdc", "cbd", "bdc", "acb"];

to something like this:

[[ 'abc', 'bca', 'acb'], ['bdc', 'cbd', 'bdc'], ['abcd']]

So far, this is what I have:

const sequence = ["abc", "abcd", "bca", "bdc", "cbd", "bdc", "acb"];

let finalSequence = [];
let sequence2 = [];
let sequence3 = [];
let sequence4 = [];
sequence.forEach(element => {
  for (const elem of element ) {
    sequence2 = sequence.filter(e => e.includes(elem) && e.length === element.length)
    sequence3 = sequence.filter(e => !e.includes(elem))
    sequence4 = sequence.filter(e => e.includes(elem) && e.length !== element.length)
    return sequence2, sequence3, sequence4
  }
})
console.log(sequence2)
console.log(sequence3)
console.log(sequence4)

finalSequence.push(sequence2, sequence3, sequence4)

This only works for the array provided but once I start testing it and playing around with it a bit more, it becomes evident this is not the proper way to go about it.

Would really appreciate any suggestions or input on how to tackle this problem. Thank you so much!

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • What is your criteria for grouping elements in that way? – Andy Oct 20 '21 at 18:25
  • 1
    Hi Andy! It's a sequence problem that each element in a specific array must have the same length and items. So the abc's, bcd's, and the abcd should be grouped in their own arrays. – MiniDracaena Oct 20 '21 at 18:34

1 Answers1

1

You could normalize each string to get sorted letters and use this as group for all similar strings.

const
    sequence = ["abc", "abcd", "bca", "bdc", "cbd", "bdc", "acb"],
    grouped = Object.values(sequence.reduce((r, s) => {
        const key = Array.from(s).sort().join('');
        (r[key] ??= []).push(s);
        return r;
    }, {}));

console.log(grouped);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Wow, thank you so much! I didn't think of grouping it as an object. This helps a lot. Thanks again and have a great day :) – MiniDracaena Oct 20 '21 at 18:38
  • 1
    Related: [How to group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key/40774759#40774759) – Stef Oct 20 '21 at 18:41