Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to sort an array in comparison to another array

let selected_variation = [{
    "type": "Capacity",
    "value": "512G",
  },
  {
    "type": "Color",
    "value": "#000000",
  }
]

let attributes = [{
    "id": "Color",
    "name": "Color",
    "type": "swatch",
    "items": [{
        "displayValue": "Green",
        "value": "#44FF03",
        "id": "Green"
      },
      {
        "displayValue": "Cyan",
        "value": "#03FFF7",
        "id": "Cyan"
      },
      {
        "displayValue": "Blue",
        "value": "#030BFF",
        "id": "Blue"
      },
      {
        "displayValue": "Black",
        "value": "#000000",
        "id": "Black"
      },
      {
        "displayValue": "White",
        "value": "#FFFFFF",
        "id": "White"
      }
    ]
  },
  {
    "id": "Capacity",
    "name": "Capacity",
    "type": "text",
    "items": [{
        "displayValue": "512G",
        "value": "512G",
        "id": "512G"
      },
      {
        "displayValue": "1T",
        "value": "1T",
        "id": "1T"
      }
    ]
  }
]

so I have these two arrays one I am creating to track the selected variation of the product from the user there is a bug in it the order of the variation in my created array depends on which order the user clicks on the input fields I need to map my array in the order of the resulted api and the variations are not fixed it actually varies according to the product so my expected output

Output

let selected_variation = [
   {"type":"Color","value":"#000000"},
   {"type":"Capacity","value":"512G"}
]

the same order the API is following

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Maybe you could try this:

const order = attributes.map((attribute) =>
  selected_variation.find((v) => v.type === attribute.id)
);

console.log(order)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading