Implement a function in JavaScript that filters an array of objects based on the value or index.
Example
Input: const arr = [ { name: "Amir", id: "1" }, { name: "Samlan", id: "2" }, { name: "Shahrukh", id: "0" }, ]; console.log(filterObject(arr, 0)); // { name: "Amir", id: "1" } console.log(filterObject(arr, "Amir")); // { name: "Amir", id: "1" } console.log(filterObject(arr, "0")); // { name: "Shahrukh", id: "0" }
One way to solve this is by using the Proxy and overriding the get method, but the problem with this is it converts the input values to a string, thus it is not easy to determine if we have to filter on index or value.
We can use an alternative approach where we will create a function that will accept the array of objects and filter value as input and based on the type of filter it will check in the object and return the appropriate value. If nothing is found we will return undefined
.
const filterObject = (arr, filter) => { // if the value of the filter is a string // check in the values of the object if(typeof filter === "string"){ for(const entry of arr){ // traverse each entry and check on value for(const [key, val] of Object.entries(entry)){ if(val === filter){ return entry; } } } } // if filter is number and can be accessed in arr else if(filter in arr){ return arr[filter]; } // if nothing is found else{ return undefined; } };
Input: const arr = [ { name: "Amir", id: "1" }, { name: "Samlan", id: "2" }, { name: "Shahrukh", id: "0" }, ]; console.log(filterObject(arr, 0)); console.log(filterObject(arr, "Amir")); console.log(filterObject(arr, "0")); console.log(filterObject(arr, "-1")); Output: // { name: "Amir", id: "1" } // { name: "Amir", id: "1" } // { name: "Shahrukh", id: "0" } // undefined