简体   繁体   中英

Order array of object by another array of object in javascript

How to order array of object by another array of object.

This is my code:

let arrayItem = [
    {
        'id': '#id1',
        'name': 'one',
        'bundle': 'bundle1'
    },
    {
        'id': '#id2',
        'name': 'two',
        'bundle': 'bundle2'
    },
    {
        'id': '#id3',
        'name': 'three',
        'bundle': 'bundle3'
    }
]

This is the array for ordering:

let orderItem = [
    {
        'id': '#id3',
        'name': 'three'
    },
    {
        'id': '#id1',
        'name': 'one',
    },
    {
        'id': '#id2',
        'name': 'two'
    }
]

I need the data like:

let resultItem = [
    {
        'id': '#id3',
        'name': 'three',
        'bundle': 'bundle3'
    },
    {
        'id': '#id1',
        'name': 'one',
        'bundle': 'bundle1'
    },
    {
        'id': '#id2',
        'name': 'two',
        'bundle': 'bundle2'
    }
]

I want to order array of objects by another array of objects by multiple keys.

Thank you

Since you have array of objects in your orderArray , you first need to find the index of that order object then get the difference of the index to get the original array sorted:

 let arrayItem = [ { 'id': '#id1', 'name': 'one', 'bundle': 'bundle1' }, { 'id': '#id2', 'name': 'two', 'bundle': 'bundle2' }, { 'id': '#id3', 'name': 'three', 'bundle': 'bundle3' } ]; let orderItem = [ { 'id': '#id3', 'name': 'three' }, { 'id': '#id1', 'name': 'one', }, { 'id': '#id2', 'name': 'two' } ]; arrayItem.sort(function(a, b){ var aIndex = orderItem.findIndex(({id, name}) => a.id===id && a.name===name); var bIndex = orderItem.findIndex(({id, name}) => b.id===id && b.name===name); return aIndex - bIndex; }); console.log(arrayItem); 

You can use Sort as suggested by @Ankit Agarwal.

Or you can make it work for you using the simple line below. This will do the trick.

var orderedItem = orderItem.map(orderObj => 
       arrayItem.find(actualObj => actualObj.id === orderObj.id))

I'm just running map on your orderItem , find ing the corresponding object on your arrayItem and then returning the object from your arrayItem.

Hope it helps..

You could take a Map for storing the index/order and then take the delta of the indices for sorting the array.

 var arrayItem = [{ id: '#id1', name: 'one', bundle: 'bundle1' }, { id: '#id2', name: 'two', bundle: 'bundle2' }, { id: '#id3', name: 'three', bundle: 'bundle3' }], orderItem = [{ id: '#id3', name: 'three' }, { id: '#id1', name: 'one', }, { id: '#id2', name: 'two' }], order = new Map(orderItem.map(({ id }, i) => [id, i])); arrayItem.sort((a, b) => order.get(a.id) - order.get(b.id)); console.log(arrayItem); 

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