Home > Software design >  How to filter an array according another array in object?
How to filter an array according another array in object?

Time:03-22

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: []},
    ]

CodePudding user response:

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

  • Related