0

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?

3
  • 1
    is options a string? Commented Nov 12, 2020 at 12:24
  • 3
    Your first array isn't valid JavaScript. Commented Nov 12, 2020 at 12:24
  • ` options: {layer:mynode:Cat}` is invalid syntax Commented Nov 12, 2020 at 12:26

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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; }

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.