0

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;
2
  • 1
    you know what's better than putting a picture of the data in the question? Putting some data in the question - it looks like you have a nested array, so you'll need to filter the second level array, not the first Commented Oct 29, 2019 at 3:05
  • 1
    It would be helpful to see a sample of the desired output. Also, what is the status of your attached code? Is it not completing, or outputting a different format than you expected? Commented Oct 29, 2019 at 3:07

2 Answers 2

1

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

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

Comments

0

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)

1 Comment

Appreciate your answer. I already got it from the answer of @David

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.