
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Entries in an Object with Specific Values in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"goods":"Wheat ", "from":"GHANA", "to":"AUSTRALIA"}, {"goods":"Wheat", "from":"USA", "to":"INDIA"}, {"goods":"Wheat", "from":"SINGAPORE", "to":"MALAYSIA"}, {"goods":"Wheat", "from":"USA", "to":"INDIA"}, ];
We are required to write a JavaScript function that takes in one such array. The goal of function is to return an array of all such objects from the original array that have value "USA" for the "from" property of objects and value "INDIA" for the "to" property of objects.
Example
const arr = [ {"goods":"Wheat ", "from":"GHANA", "to":"AUSTRALIA"}, {"goods":"Wheat", "from":"USA", "to":"INDIA"}, {"goods":"Wheat", "from":"SINGAPORE", "to":"MALAYSIA"}, {"goods":"Wheat", "from":"USA", "to":"INDIA"}, ]; const findDesiredLength = (arr = [], from = 'USA', to = 'INDIA') => { const filtered = arr.filter(el => { if(el.from === from && el.to === to){ return true; } }); const { length: l } = filtered || []; return l; }; console.log(findDesiredLength(arr));
Output
And the output in the console will be −
2
Advertisements