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
Updated on: 2020-11-23T06:17:46+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements