Recursive search in an array of objects!
Problem Statement: Search if a value is present in an array of objects.
Table of contents
If the given value is present in a particular key i.e. "color" in our case return the "index" otherwise return "-1"
Let's say we have the following array of objects:
const colorSet = [
{ color: "red", value: "#f00" },
{ color: "green", value: "#0f0" },
{ color: "blue", value: "#00f" },
{ color: "cyan", value: "#0ff" },
{ color: "magenta", value: "#f0f" },
{ color: "yellow", value: "#ff0" },
{ color: "black", value: "#000" }
];
Approach & Solution:
Create one function which will take the three parameters:
An array of objects [see above colorSet]
A search value
Length of the array - 1 (last index of the array)
Add base condition if the length is less than 0. That means we have not got the search value. Return from there.
Extract obj from an array using an index parameter.
Check if the object has a search value.
If the value is present return the index otherwise return the same function with a decrement last index of the array.
Last print the index.
Code:
const searchMe = (arr, search, index) => {
// base condtion
if (index < 0) {
return index;
}
// processing
const obj = arr[index];
const ans = obj.color === search;
/**
* if value present return the index otherwise
* return the searchMe with decreament the last index of array
*/
if (ans) {
return index;
} else {
return searchMe(arr, search, index - 1);
}
}
let result = null;
result = searchMe(colorSet, 'nikhilkrdwivedi', colorSet.length - 1);
console.log({ result });
result = searchMe(colorSet, 'blue', colorSet.length - 1);
console.log({ result });
Output:
You will able to see the following output in the console.
Case 1: As you can see 'nikhilkrdwivedi' is not present in "color" key that's why the index is -1 and the result is logged as -1.
Case 2: 'blue' is present at the 2nd index of the array. Hence the result is logged as 2.
{ result: -1 }
{ result: 2 }
Happy Codings ๐ง๐ผโ๐ป