简体   繁体   中英

Sort array based on values in another array

I have 2 arrays as follows.

Array 1

let array1 = [

  {
    name:1,
    options: {layer:mynode:Cat}
  },
  {
    name:randomName,
    options: {layer:mynode:Dog}
  },
  {
    name:randomName2,
    options: {layer:mynode:Lion}
  }

]

And the next array

Array 2

let array2 = ["Dog","Lion","Cat"]

I want to sort the array1 according to the data order in array2. I have tried something like this but it's giving me a undefined result

sortedArr = array2.map((object,key) => array1[((options.layers).split(':'))[1]]);

Can someone help me with this?

 let array1 = [ { name: 1, options: { layer: "mynode:Cat" }, }, { name: 2, options: { layer: "mynode:Dog" }, }, { name: 3, options: { layer: "mynode:Lion" }, }, ]; let array2 = ["Dog", "Lion", "Cat"]; array1.sort((a, b) => { return array2.indexOf(a.options.layer.split(":")[1]) > array2.indexOf(b.options.layer.split(":")[1])? 1: -1; }); console.log(array1);

Either way, take the wanted value from the property option and from an object a numerical order value for a delta of both items fopr sorting.

 const getPart = string => string.slice(1, -1).split(':')[2], array1 = [{ name: 1, options: '{layer:mynode:Cat}' }, { name: 'randomName', options: '{layer:mynode:Dog}' }, { name: 'randomName2', options: '{layer:mynode:Lion}' }], array2 = ["Dog", "Lion", "Cat"], order = Object.fromEntries(array2.map((v, i) => [v, i + 1])); array1.sort((a, b) => order[getPart(a.options)] - order[getPart(b.options)]); console.log(array1);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

let array1 = [

  {
    name:'1',
    options: {layer:'Cat'}
  },
  {
    name:'randomName',
    options: {layer:'Dog'}
  },
  {
    name:'randomName2',
    options: {layer:'Lion'}
  }

]

let array2 = ["Dog","Lion","Cat"]
let sortedArr = []

array2.forEach(elem => sortedArr.push(array1[(array1.findIndex(elemArr1 => elemArr1.options.layer === elem))]))

console.log(sortedArr)

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