Home > Software design >  How can I organize an array based on a pattern?
How can I organize an array based on a pattern?

Time:10-21

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!

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related