Home > database >  Javascript - Sort array of object based on another array
Javascript - Sort array of object based on another array

Time:09-28

I have an array of object and will like to sort the properties of each object according to sequence of another array

let arrToSort = [
   { Architect: 'Terry', Client: 'AZ', ClientType: 'Kids', Location: 'USA'},
   { Architect: 'Mary', Client: 'XY', ClientType: 'Clothes', Location: 'Germany'},
   { Architect: 'Jerry', Client: 'BC', ClientType: 'Construction', Location: 'Canada'}
];

let accordingTo = ["ClientType", "Architect", "Location", "Client"];

Should look like:

finalArr = [
   { ClientType: 'Kids', Architect: 'Terry', Location: 'USA', Client: 'AZ'},
   { ClientType: 'Clothes', Architect: 'Mary', Location: 'Germany', Client: 'XY'},
   { ClientType: 'Construction', Architect: 'Jerry', Location: 'Canada', Client: 'BC'}
]

CodePudding user response:

let arrToSort = [{ Architect: 'Terry', Client: 'AZ', ClientType: 'Kids', Location: 'USA' }, { Architect: 'Mary', Client: 'XY', ClientType: 'Clothes', Location: 'Germany' }, { Architect: 'Jerry', Client: 'BC', ClientType: 'Construction', Location: 'Canada' }];
let accordingTo = ["ClientType", "Architect", "Location", "Client"];

let finalArray = arrToSort.map(itm => Object.keys(itm).sort((a, b) => accordingTo.indexOf(a) - accordingTo.indexOf(b)).reduce((tr, key) => {
  tr[key] = itm[key]
  return tr
}, {}))

console.log(finalArray)

CodePudding user response:

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)

let arrToSort = [{
    Architect: 'Terry',
    Client: 'AZ',
    ClientType: 'Kids',
    Location: 'USA'
  },
  {
    Architect: 'Mary',
    Client: 'XY',
    ClientType: 'Clothes',
    Location: 'Germany'
  },
  {
    Architect: 'Jerry',
    Client: 'BC',
    ClientType: 'Construction',
    Location: 'Canada'
  }
];
let accordingTo = ["ClientType", "Architect", "Location", "Client"];

function sortByKeys(arr, keyOrder) {
  let newArray = [];
  arr.map((obj) => {
    const newObj = {};
    keyOrder.forEach((key) => {
      newObj[key] = obj[key];
    })
    newArray.push(newObj)
    return obj;
  });
  return newArray;
}
arrToSort = sortByKeys(arrToSort, accordingTo);

console.log(arrToSort);

  • Related