1

I'm trying to sort an array of strings based on an array of objects. (The array will not have the same amount of items the object has.)

Here's the code:

const myObject = [
    {
        title: 'Some string'
    },
    {
        title: 'another string'
    },
    {
        title: 'Cool one'
    }
];

const array = ['Cool one', 'Some string']; // Sort this array based on 'myObject'
1
  • 1
    based on what criteria on array of objects you want to sort. Question is not very clear though Commented Oct 10, 2019 at 4:02

3 Answers 3

3

You can generate a table of indices by which to sort your array like this:

const myObject = [
  { title: 'Some string' },
  { title: 'another string' },
  { title: 'Cool one' }
];
const indices = Object.fromEntries(
  myObject.map(
    ({ title }, index) => [title, index]
  )
);
const array = ['Cool one', 'Some string'];

array.sort((a, b) => indices[a] - indices[b]);

console.log(array);

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

Comments

2

You can use reduce & findIndex. Inside reduce callback function use findIndex to check if the element exist in myObject. If so then get the index and using this add the value in accumulator array

const myObject = [{
    title: 'Some string'
  },
  {
    title: 'another string'
  },
  {
    title: 'Cool one'
  }
];

const array = ['Cool one', 'Some string'];

let newArray = array.reduce(function(acc, curr) {
  let findIndex = myObject.findIndex(a => a.title.toLowerCase().trim() == curr.toLowerCase().trim());
  if (findIndex !== -1) {
    acc.push(myObject[findIndex])
  }
  return acc;
}, []);

console.log(newArray)

1 Comment

I'm trying to sort the array based on the object.
0

I think you can use Array.findIndex() to help you out on this one, in conjunction with Array.sort()

const objectArray = [
  { title: 'Some string' },
  { title: 'another string' },
  { title: 'Cool one' }
]

const stringArray = [
  'Cool one',
  'Some string'
]

const sortFromObject = (a, b) => {

  // get the indexes of the objects
  const idxA = objectArray
     .findIndex(obj => obj.title === a)
  const idxB = objectArray
     .findIndex(obj => obj.title === b)

  // if it comes first in the object array,
  // sort this item up, else sort it down
  return idxA - idxB
}

stringArray.sort(sortFromObject)

1 Comment

That's right, I always forget sort expects just a positive or negative, not necessarily 1.

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.