Home > OS >  sorting 2 array in ascending order javascript
sorting 2 array in ascending order javascript

Time:08-24

I have 2 arrays

let array1 = [
{
    "label": "4kg",
    "value": "4kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 491,
    "optionName": "Size"
},
{
    "label": "1.3kg",
    "value": "1.3kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 699,
    "optionName": "Size"
},
{
    "label": "300g",
    "value": "300g",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 639,
    "optionName": "Size"
},
{
    "label": "10kg",
    "value": "10kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 492,
    "optionName": "Size"
}
]

below is array2

let array2 = ['300g', '1.3kg', '4kg', '10kg']

so i need my final array sorting of arrayy value like below

let array3 = [
{
    "label": "300g",
    "value": "300g",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 639,
    "optionName": "Size"
   
},
{
    "label": "1.3kg",
    "value": "1.3kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 699,
    "optionName": "Size"
},
{
    "label": "4kg",
    "value": "4kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 491,
    "optionName": "Size"
     
},
{
    "label": "10kg",
    "value": "10kg",
    "optionId": "x_size",
    "mapKey": "sku-Food_x_size",
    "valueItem": 492,
    "optionName": "Size"
}
]

Any idea how i can map this ?

CodePudding user response:

You can provide a comparator to Array.prototype.sort():

array1.sort((a, b) => array2.indexOf(a.value) - array2.indexOf(b.value));

CodePudding user response:

As @alberto said you need to use sort method. But i suggest to precalculate indexes before sorting for better performance.

array1.forEach(record => { record._order = array2.indexOf(record.value) })
array1.sort((a, b) => a._order - b._order)
array1.forEach(record => { delete record._order })

Also it may be better to convert weights to grams and sort array by those values, without extra array at all.

  • Related