Home > Back-end >  find possible pair from array of string on this particular case
find possible pair from array of string on this particular case

Time:09-19

I want to generate possible pairs from string array

this is what I got now:

const findPossiblePair = (array) => {
  const results = [];

  for (let i = 0; i < array.length - 1; i  ) {
    for (let j = i   1; j < array.length; j  ) {
      results.push(`${array[i]}-${array[j]}`);
    }
  }

  return results;
};

const result = findPossiblePair(['michael', 'john', 'annie'])

console.log(result)

currently it generates: ["michael-john", "michael-annie", "john-annie"]

I want it to be: ["michael-john", "john-michael", "michael-annie", "annie-michael"]

notice michael becomes some sort of "anchor" because it's there in all of the elements

e.g.

if the anchor is "annie", it generates: ["annie-michael", "michael-annie", "annie-john", "john-annie"]

I believe I need to add a parameter on the function for the anchor

but I'm in complete stuck

please help me

CodePudding user response:

I would use Array.reduce to iterate the names instead and just push the pairs to the result array when the name being iterated is not the anchor:

const findPossiblePair = (array, anchor) =>
  array.reduce((acc, name) => {
    if (name != anchor) {
      acc.push(`${anchor}-${name}`);
      acc.push(`${name}-${anchor}`);
    }
    return acc;
  }, [])

const result = findPossiblePair(['michael', 'john', 'annie'], 'annie')

console.log(result)

CodePudding user response:

@nick solution is great. but just for info , you can add one more line in your existing code.

 for (let i = 0; i < array.length - 1; i  ) {
    for (let j = i   1; j < array.length; j  ) {
      results.push(`${array[i]}-${array[j]}`);
      results.push(`${array[j]}-${array[i]}`); // add this line
      //  [...results,`${array[i]}-${array[j]}`,`${array[j]}-${array[i]}`]  //or replace with this
    }
  }
  • Related