简体   繁体   中英

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

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

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