Count number of entries in an object having specific values in multiple keys JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 23-Nov-2020 06:17:30
Advertisements