Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter an array according another array in object?

I have an array:

const arr = [
    {id: 1, text: "hello", likes: [1,2,5]},
    {id: 2, text: "text", likes: []},
    {id: 3, text: "example", likes: [1]}
]

how to filter it according to the length of likes array i.e array should be like this:

const arr = [
        {id: 1, text: "hello", likes: [1,2,5]},
        {id: 3, text: "example", likes: [1]},
        {id: 2, text: "text", likes: []},
    ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use Array.prototype.sort() with parameters a,b and compare the length property of the likes property

READ MORE HERE:
javascript Array.prototype.sort

const arr = [
    {id: 1, text: "hello", likes: [1,2,5]},
    {id: 2, text: "text", likes: []},
    {id: 3, text: "example", likes: [1]}
]

arr.sort(function(a,b) { 
   return b.likes.length - a.likes.length;
});

for(let a = 0; a < arr.length; a++){
  console.log(arr[a]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading