-2

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);
      }
    }
Usman Amir
  • 51
  • 1
  • 8
  • Please show any attempt that you have made to solve this issue yourself. You are expected to have made an attempt that we can then help you debug. https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users Also review [ask] – Taplar Mar 27 '20 at 22:27
  • 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); } } – Usman Amir Mar 27 '20 at 22:34
  • its messing my head around – Usman Amir Mar 27 '20 at 22:35
  • Can you edit the question and put it in there please? It's hard to read code in the comments and is not the correct place to put it – Taplar Mar 27 '20 at 22:35
  • i edited the question – Usman Amir Mar 27 '20 at 22:39

1 Answers1

0

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);
Taplar
  • 24,788
  • 4
  • 22
  • 35