Tauras
Tauras

Reputation: 3904

Sort array of objects by value in array of each object

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

Upvotes: 0

Views: 42

Answers (1)

Nick
Nick

Reputation: 147216

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

Upvotes: 1

Related Questions