Exploring Angular: Techniques for searching within nested arrays

I am looking for a function that can search and filter the largest value in a nested array, and then return the parent scope.

Here is an example of my array:

 data = {"people": 
   [{"male": [
     {"name": "Bob" ,"age": "32"}, 
     {"name":"Mike", "age":"22"}
    ]}, 
   {"female": [
     {"name":"Jessica", "age": "24"}, 
     {"name":"Ann", "age": "23"}
   ]}]} 

I want to find the highest age value among all people and then return either the male or female array (in this case it would be the male array).

In JavaScript, I could potentially use something like:

largest = array.reduce((x, y) ->
      if x > y then x else y
    )
    console.log largest

How can I implement this logic with a nested array?

Alternatively, is there a way to utilize angular's $filter for this task?

Answer №1

For guidance on searching a nested object, refer to this resource: Explore how to locate a key deep within a nested object

You can then iterate through all elements in your array to perform the search.

If you can ensure the structure of your array and its nested objects, I recommend a slightly different approach. First, iterate through the array (male/female) and for each, examine the persons to find their ages. While not an exact code snippet, here is something along those lines:

var age = 0;
data["people"].forEach(function(item) { 
    for (var key in item) {
        if (item.hasOwnProperty(key)) {
            item[key].forEach(function(person) {
                if (person.age > age) {
                    age = person.age;
                }
            });
        }
    }
});
console.log(age);

Answer №2

Despite its unattractive data representation, let's dive into the code:

var info = {"people": 
   [{"men": [
     {"name": "Bob" ,"age": "32"}, 
     {"name":"Mike", "age":"22"}
    ]}, 
   {"women": [
     {"name":"Jessica", "age": "24"}, 
     {"name":"Ann", "age": "23"}
   ]}]};

function getOldest(array) {
  var maxAge = 0;
  array.forEach(function(person) {
    if (person.age > maxAge) maxAge = person.age;
  })
  return maxAge;
}

var oldestAge = 0;
var oldestArray;
for (var j = 0; j < info.people.length; j++) {
  var subArray = info.people[j][Object.keys(info.people[j])[0]];
  var currentOldest = getOldest(subArray);
  if (currentOldest > oldestAge) {
    oldestAge = currentOldest;
    oldestArray = subArray;
  }
}

console.log('The eldest age is: ' + oldestAge)
console.log(oldestArray);

Experience this code in action at https://jsfiddle.net/ave5hcLu/

This code assumes a fixed data structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I append a hash to a URL using JavaScript without causing the page to scroll?

Is it possible to add a hash to the URL without scrolling the page using JavaScript? I navigate to the page I scroll down I click on a link that adds a hash (for example: http://www.example.com/#test) The page should not scroll back to the top. What is ...

Enhancing User Experience: Creating a Vue Button Component for Adding Items to Cart with the Power of Axios and Laravel Backend Integration

I have recently developed a Vue3 shopping cart with an "Add One" button feature. When the user clicks this button, it updates an input field of type "number" and sends a request to update the database using Axios along with Laravel's createOrUpdate me ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

Having trouble reaching an injected dependency beyond the controller method

Can an injected dependency on a controller be accessed outside of it? function clientCreateController(ClientsService, retrieveAddress) { var vm = this; vm.searchCep = searchCep; } function searchCep(cep) { retrieveAddress.find(cep) .success ...

Implement a feature in JSP that allows users to dynamically add or remove fields before submitting the data to the database

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

What is the best method to detect a change in scroll position on a webpage using JavaScript?

Is there a way to trigger an event when the page's scroll position changes? I'm interested in creating a dynamic table of contents similar to (where the active item changes as you scroll). Can this be achieved without directly accessing the cu ...

How to round whole numbers to whole numbers using JavaScript?

Looking to manipulate some numbers in JavaScript. Let's say we have x = 320232, y = 2301, and z = 12020305. The goal is to round these numbers to the nearest tens, hundreds, or thousands place. Thus, we want them to become x = 320000, y = 2300, and z ...

ng-init assign value to a new object

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('Al ...

Sending a file to the jqGrid handler

Currently, I am using Grails in combination with jqGrid and attempting to implement a rather unique feature. My goal is to allow users to upload a file which will then be sent to the jqGrid controller and used as a filter for the data displayed on the grid ...

How can I use AngularJS to save selected assets?

<div style="z-index: 1; position: absolute"ng-show="ctrl.company.selected"> <div style="" ng-repeat="Asset in ctrl.company.selected.Assets"> <div class="pd-5"style="width: 300px; background-color: white; border-bottom: gray solid ...

Exploring Next.js: Advanced capabilities of shallow routing in combination with dynamic routes

Many people seem to be confused about the behavior of shallow routing with dynamic routes in Next.js. When attempting shallow routing, the page is refreshed and the shallow option is ignored. Let's consider a scenario where we start on the following ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

Upon clicking, the reset function will be triggered

I have a jQuery code that includes a click event on td elements. After clicking on a td, an input field with text appears and the focus is set at the end of the text. However, I want to remove the focus after the initial click so that I can click in the ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...

The elegant-admin template's mobile navigation toggle is missing

I recently downloaded an admin theme and added the CSS to my Django static files. However, after doing so, the mobile toggle feature disappeared. I double-checked all the CSS and JS links in the index template, and they are correctly linked to the paths, b ...

Tips on setting dynamic headers in tabulator

Is there a way to dynamically set the header name passed from JSON? Additionally, how can I hide multiple columns in Tabulator instead of just one? I would also like to be able to show/hide multiple columns on button click. These questions pertain to a co ...

Invoking an express route using JavaScript

After successfully defining some routes, including a text input search field at the top of the page, I created a listener function as shown below: $('#tags').keypress(function(e) { if (e.keyCode == 13 && document.getElementById('t ...

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...