简体   繁体   中英

Sorting second array with respect to first array in javascript

For eg.My

Mainarray = [{label:a,value:5} ,
{label :b , value :4 },
{label :c , value :10},
{label :d , value :5}]

and my array to be sorted is

array1 = [ {label :c ,value 5},{label :a ,value:2}

after array1 is sorted it must be like this

sortedarray= [{label:a,value :2} ,
{label :b , value :0 },
{label :c , value :5},
{label :d , value :0}]

so basically, it must be sorted with respect to MainArray Label, and also if that label doesnt exist in array1, it should append the same label on same index with value 0

You need to map to the dataset you want, then sort the mapped dataset. Here is an example. Hope that helps!

 const array = [ { label: 'c', value: 5 }, { label: 'b', value: 4 }, { label: 'a', value: 10 }, { label: 'd', value: 5 } ] const toSort = [ { label: 'b', value: 1 }, { label: 'a', value: 5 }, { label: 'c', value: 2 } ]; const mapToSort = array.map(_ => { const item = toSort.find(x => x.label === _.label); return item || { label: _.label, value: 0 }; }) const getIndex = item => array.findIndex(_ => _.label === item.label); const sorted = mapToSort.sort((a, b) => getIndex(a) - getIndex(b)); console.log(JSON.stringify(sorted));

You could collect the new values in a Map and map the data array with new values or zero.

 var data = [{ label: 'a', value: 5 }, { label: 'b', value: 4 }, { label: 'c', value: 10 }, { label: 'd', value: 5 }], array = [{ label: 'c', value: 5 }, { label: 'a', value: 2 }], values = new Map(array.map(({ label, value }) => [label, value])), result = data.map(({ label }) => ({ label, value: values.get(label) || 0 })); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM