0

I am not sure if I wrote this question correctly, however.. I have this array of objects:

[
 {
   foo: 'Google',
   bar: 'Bing',
   pro: [
      'One',
      'Two',
      'Three'
   ]
 },
 {
   foo: 'Random string',
   bar: 'Something',
   pro: [
      'Five'
   ]
 },
 {
   foo: 'String',
   bar: 'Game',
   pro: [
      'Ten',
      'One'
   ]
 },

 // ...

]

And I need to sort it by the pro property where any of the array elements contains text. The umber of array elements is unknown, but at least 1.

Where I am stuck with the logic:

var text = 'On';

var results = arr.sort(function(a, b) {
  // do another loop, than count and than check?
});

In this example, and after successful sort function, order of objects should become 0, 3, 2 or 3, 0, 3, because On exists in two of them.

Thanks for any help

2
  • Which should be the rule to select which one come first? Commented Nov 2, 2019 at 22:39
  • Does not matter. There is deeper logic behind that, but result is this, and i need to sort this. Commented Nov 2, 2019 at 22:41

1 Answer 1

1

You can write a short function to check if a value starts with the value of text and then use that as an input to pro.some() in your sort function, sorting b before a to sort in descending order.

const arr = [{
    foo: 'Google',
    bar: 'Bing',
    pro: [
      'One',
      'Two',
      'Three'
    ]
  },
  {
    foo: 'Random string',
    bar: 'Something',
    pro: [
      'Five'
    ]
  },
  {
    foo: 'String',
    bar: 'Game',
    pro: [
      'Ten',
      'One'
    ]
  }
];
const text = 'On';
const hastext = v => v.indexOf(text) == 0;

arr.sort((a, b) =>
  b.pro.some(hastext) - a.pro.some(hastext)
);

console.log(arr);

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

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.