Search code examples
javascriptalgorithmsortinghashmaphashtable

Is there any way to make match each index of array with other within array but not with itself


Here is my initial array

const a = [A,B,C,D];

i am trying to achieve result like that

const finalarray = [
{key1 : A , key2 : B},{key1 : A , key2 : C},{key1 : A , key2 : D},
{key1 : B , key2 : A},{key1 : B , key2 : C},{key1 : B , key2 : D},
{key1 : C , key2 : A},{key1 : C , key2 : B},{key1 : C , key2 : D},
{key1 : D , key2 : A},{key1 : D , key2 : B},{key1 : D , key2 : C}]

you can see in every object of the final array there is not compare with the same index like {key1: A, key2: A} it will be wrong I am trying to achieve is that to compare each index of the array but not itself I am basically merging in an object not comparing it. it will be used next for sorting. Thanks

what. i try

what i try

render() {
    let arraytoRender = null;
    let newarr = [];
    if (this.state.array) {
      let arraytoRender1 = [];
      this.state.array.map(p => {
        arraytoRender1.push(p.nom);
        newarr.push(p.nom);
      });
      arraytoRender = arraytoRender1.join();
    }
    let i;

    for (i = 0; i < newarr.length; i++) {
      if (newarr[i] !== newarr[i]) {
        console.log(newarr);
      }
    }

Solution

  • If you're not worried about supporting IE, then you can map the original array to a new array, ignoring the iterated element each time when making the permutations, and at the end flatten the array.

    const a = ['A', 'B', 'C', 'D'];
    
    const output = a.map((key1, index, array) => {
      let otherElements = array.filter((x, i) => i != index);
      
      return otherElements.map(key2 => ({ key1: key1, key2: key2 }));
    }).flat();
    
    console.log(output);

    Or, you could straight up just do the permutations and then remove the ones that shouldn't be there.

    const a = ['A', 'B', 'C', 'D'];
    
    const output = a.map((key1, index, array) => {
      return array.map(key2 => ({ key1: key1, key2: key2 }));
    }).flat().filter(x => x.key1 != x.key2);
    
    console.log(output);