Alyssa Reyes
Alyssa Reyes

Reputation: 2439

Filter nested array of objects

How can I filter this kind of array? I want to filter it based on my condition below

enter image description here

let employeeLeaves = isEmployeeLeave;

const calendarDates = value.toString();
const formatCalendarDates = moment(calendarDates).format('YYYY-MM-DD');

const filteredData = employeeLeaves.filter(function(item) {
 return item.startDate == formatCalendarDates;
});

return filteredData;

Upvotes: 0

Views: 89

Answers (2)

David
David

Reputation: 16287

Idea:

  • flatten the nested array into an simple array
  • filter the result from the simple array

Method I: Quick and concise

const result = [].concat(...input).filter(item =>  item.startDate === formatCalendarDates);

Method II: Using a library (e.g. Ramda) to flatten it

R.flatten(data).filter(item => item.key === 'a');

See the live result here.

Method III: do it manually:

const data = [ 
        [
            { key: 'a', value: 1 },
            { key: 'b', value: 2 },
            { key: 'c', value: 3 },
            { key: 'a', value: 4 },
            { key: 'b', value: 5 },
            { key: 'a', value: 6 }
        ], [
            { key: 'b', value: 7 },
            { key: 'b', value: 8 },
            { key: 'a', value: 9 }
        ], [
            { key: 'c', value: 10 },
            { key: 'b', value: 11 },
            { key: 'b', value: 12 }
        ]
    ];


const flat = data => {
    let output = [];
    data.map(arr => output = [... arr, ... output]) ;
    return output;
}


const result = flat(data).filter(item => item.key === 'a');
console.log(result);

Upvotes: 1

Arman Charan
Arman Charan

Reputation: 5797

See Array.prototype.flat() and Array.prototype.filter() for more info

// Input.
const employees = [[{id: '4930'}], [{id: '4328'}]]

// Predicate.
const matchingIdPredicate = (employee, id) => employee.id === id

// Filter.
const employeesWithMatchingId = employees.flat(1).filter(employee => matchingIdPredicate(employee, '4930'))

// Proof.
console.log('Employees with matching id:', employeesWithMatchingId)

Upvotes: 0

Related Questions