0

I am trying to sort object of arrays by arrays length, for example, i try to get from this object array where length more than 3

 {
  friend: [
    { id: 0, name: 'A' },
    { id: 1, name: 'V' },
    { id: 2, name: 'C' },
    { id: 3, name: 'D' }
  ],
  people: [ { id: 0, name: 'A' }, { id: 1, name: 'B' } ]  
}

and the result will array friend. I try to do this

function getPart (obj) {
    for (let key in obj) { 
        if (obj[key].length>=4) {
            console.log(obj[key]);
        }
}}

but I want to try to do it with filter object but I have no idea how to make it

3
  • I'm not entirely sure of what you are trying to do. Could you elaborate what the output should look like? Welcome to SO by the way! Commented Apr 8, 2021 at 7:43
  • I want to use filter instead if Commented Apr 8, 2021 at 7:47
  • 1
    Ok. I got confused by the title. No sorting is required? You simply want to find the friend object? Commented Apr 8, 2021 at 8:02

2 Answers 2

2

We can achieve that using Object.entries() and reduce() function.

Here's an example:

JS

 let data = {
  friend: [
    { id: 0, name: 'A' },
    { id: 1, name: 'V' },
    { id: 2, name: 'C' },
    { id: 3, name: 'D' }
  ],
  people: [ { id: 0, name: 'A' }, { id: 1, name: 'B' } ]  
}

// Convert first the object to an array using Object.entries so we can loop it using reduce() function
// Then we make a condition statement if the object's length is >= 4, then we'll filter that to the new object.
let new_data = Object.entries(data).reduce((a, b) => a = {...a, ...(b[1].length >= 4 ? {[b[0]]: b[1]} : {})} ,{})
console.log(new_data) // Expected result: { friend: [Object] }

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

Comments

0

Just one line:

Object.values(obj).filter(ob => ob.length >= 4);

const ob = {
  friend: [
    { id: 0, name: 'A' },
    { id: 1, name: 'V' },
    { id: 2, name: 'C' },
    { id: 3, name: 'D' }
  ],
  people: [ { id: 0, name: 'A' }, { id: 1, name: 'B' } ]  
}



function getPart (obj) {
    const filtered = Object.values(obj).filter(ob => ob.length >= 4);
    console.log(filtered);
}


getPart(ob);

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.