Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Count number of entries in an object having specific values in multiple keys 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
