sumn2u / learn-javascript

A book that teaches JavaScript πŸ“—πŸ’»πŸ“–
https://javascript.sumankunwar.com.np
Apache License 2.0
922 stars 147 forks source link

Adding Recursive functions to functions chapter #172

Closed vaibhavpnimkar closed 1 year ago

vaibhavpnimkar commented 1 year ago

Is your feature request related to a problem? Please describe. I'm always frustrated when I need to navigate through a deeply nested data structure and extract specific values. It's time-consuming and error-prone.

Describe the solution you'd like I would like to see a recursive function that can traverse complex data structures and extract values efficiently. This function should be able to handle any level of nesting.

Describe alternatives you've considered One alternative could be using nested loops, but that can lead to code duplication and reduced code clarity. A recursive function is a more elegant and maintainable solution.

Additional context Add any other context or screenshots about the feature request here.


// Example of a recursive function to extract values from a nested data structure
function extractValues(data, target) {
  if (Array.isArray(data)) {
    for (let item of data) {
      extractValues(item, target);
    }
  } else if (typeof data === 'object') {
    for (let key in data) {
      extractValues(data[key], target);
    }
  } else if (data === target) {
    // You found the value, do something with it
    console.log('Found target value:', data);
  }
}

// Usage example
const nestedData = {
  key1: 'value1',
  key2: [1, 2, 3, 'value2'],
  key3: {
    key4: 'value3',
    key5: [4, 'value4'],
  };

extractValues(nestedData, 'value4');
Shashankpantiitbhilai commented 1 year ago

assign it to me please

vaibhavpnimkar commented 1 year ago

@Shashankpantiitbhilai you can make a pr it will get merged ig if it is good enough i am not a maintainer but author of this issue'