What is the best way to organize two separate arrays based on a single shared variable?

I have two separate arrays containing information. One array includes the title of each national park and other related data, while the second array consists of alerts from the entire NPS system. The common factor between these arrays is the parkCode. How can I organize them by national park? For instance:

  1. Yellowstone National Park - alert from Yellowstone
  2. Arches National Park - alert from Arches

Here is a snippet of the data I am dealing with:

National Park Names:

 0:
 description: "."
 designation: "National Park"
 directionsInfo: "From Boston take I-95 north to Augusta, Maine, then 
 Route 3 east to Ellsworth, and on to Mount Desert Island. For an 
 alternate route, continue on I-95 north to Bangor, Maine, then take 
 Route 1A east to Ellsworth. In Ellsworth, take Route 3 to Mount Desert 
 Island."
 directionsUrl: "http://www.nps.gov/acad/planyourvisit/directions.htm"
 fullName: "Acadia National Park"
 id: "6DA17C86-088E-4B4D-B862-7C1BD5CF236B"
 latLong: "lat:44.30777545, long:-68.30063316"
 name: "Acadia"
 **parkCode: "acad"**
 states: "ME"
 url: "https://www.nps.gov/acad/index.htm"

Example Alert:

113:
category: "Park Closure"
description: "The Elwha area is closed indefinitely to vehicle traffic 
beyond Madison Falls parking lot due to extensive flood damage to the 
Olympic Hot Springs Road. There is limited parking and turnaround space 
at the Madison Falls parking area."
id: "84646EA9-1DD8-B71B-0BD7AECDC56BD8AE"
**parkCode: "acad"**
title: "Elwha (Olympic Hot Springs) Road Closed to Vehicle Access"
url: "https://www.nps.gov/olym/planyourvisit/current-road-conditions.htm"

Answer №1

If your alerts are stored as JavaScript objects in an array named alerts, you can categorize them by park in the following way:

const alertsByPark = {};
alerts.forEach(alert => {
  // Check if there are any alerts already recorded for this park, if not, add the park as a key to the alertsByPark object
  if (!alertsByPark[alert.parkCode]) alertsByPark[alert.parkCode] = [];
  alertsByPark[alert.parkCode].push(alert);
});

The data structure of alertsByPark will now look like this:

{
  acad: [...],
  ...
}

Each parkCode has a corresponding key with an array containing all alerts from that park.

To display the data in the format shown in your query, where each alert is listed under the formal name of the park referenced by its parkCode, you can use the find method on the parks array to retrieve complete park information based on the parkCode mentioned in the alert.

alerts.forEach((alert, i) => {
  // Find the park with the parkCode matching the alert's parkCode
  const park = parks.find(({ parkCode }) => parkCode === alert.parkCode);
  console.log(`${i}. ${park.fullName} - ${alert.description}`);
})

This assumes you have the alerts stored in an array called alerts and the parks in an array named parks. The output will be in a format similar to:

1. Acadia National Park - The Elwha area is closed indefinitely to...
2. park name - alert description

and so on.

Answer №2

parks.map(park => {
 park.alerts = alerts.filter(alert => alert.parkCode === park.parkCode)
 return park
})

This code snippet generates a parks array with an additional property 'alerts' that contains an array of corresponding alerts.

For example:

const parks = [
 { name: 'Yellowstone', parkCode: 'ys' },
 { name: 'Arcadia', parkCode: 'ar' },
 { name: 'Arches', parkCode: 'arch' },
 { name: 'A park without alerts', parkCode: 'PARK' }
 ]

const alerts = [
 { description: 'Alert 1', parkCode: 'ys' },
 { description: 'Alert 2', parkCode: 'ys' },
 ...
]

 let parksWithAlerts = parks.map(park => {
   park.alerts = alerts.filter(alert => alert.parkCode === park.parkCode)
   return park
 })

 console.dir(parksWithAlerts[0])

{ name: 'Yellowstone',
  parkCode: 'ys',
  alerts:
   [ { description: 'Alert 1', parkCode: 'ys' },
   ...
   ] }

Merged alerts

let parksWithAlerts = parks.map(park => {
   park.alerts = alerts.filter(alert => alert.parkCode === park.parkCode)
   return park
 }).map(park =>{
    park.alerts = park.alerts.map(alert => alert.description).join(' - ')
    return park
 })

console.dir(parksWithAlerts[0])

{ name: 'Yellowstone',
  parkCode: 'ys',
  alerts: 'Alert 1 - Alert 2 - Alert 3  - Alert 4 - Alert 7 - Alert 9 - Alert 10 - Alert 12 - Alert 15' }

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

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

Combining arrays into one

Let's kick things off with the following code: $checkIpaddresses = $wpdb->get_results( $wpdb->prepare("SELECT affiliateID, source FROM am_ipaddress WHERE affiliateID = $affiliateID")); foreach ($checkIpaddresses as $ipaddress) { $ipSource ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

Out of nowhere, JavaScript/jQuery ceased to function

Everything was running smoothly on my website with jQuery Ui until I changed the color, and suddenly everything stopped working. Any ideas why this happened? I even tried writing the JavaScript within the HTML file and linking it as a separate .js file, bu ...

Can the output of the "npm run build" command, which consists of static files, be transformed back into a fully functional project?

I possess static JavaScript build files without access to the source code that produced them. Unfortunately, the previous developer is no longer around to provide insight. Is there a way to deconstruct these files? ...

Exploring the process of adding a new node to a JSON file with JsonPath

I'm currently working on JSON manipulation and encountering some issues. My goal is to insert or update a path in a JSON object. If the path does not exist, I want it to be created, and then I can insert a new value. If the path already exists, I aim ...

Identical IDs appearing in multiple buttons causing a conflict

I am currently loading content from external HTML files, specifically page1.html and page2.html. Although everything is the same except for the pictures and text, I am encountering an issue with the close button. It only closes page1.html.Feel free to chec ...

Prevent Xdebug from processing multiple requests

One recurring issue I encounter in my app is calling an API endpoint every 60 seconds. However, when I attempt to debug using Xdebug, stepping through the controller associated with that endpoint often takes longer than a minute. This results in another re ...

Issue: Module 'ansi-styles' not found when using AngularJS and Yeoman generator

Previously my code was functioning perfectly, but now it seems to have suddenly stopped working. Attempting yo angular:route api resulted in the following error message: Error: Cannot find module 'ansi-styles' at Function.Module._resolveFilen ...

Converting a Date in PHP and Encoding it in JSON Format

I have a MySQL query that looks like this: <?php $sql = "SELECT * FROM my_table"; $result = mysql_db_query($DBname,$sql,$link) or die(mysql_error()); $rows = array(); while($r = mysql_fetch_assoc($result)) { $rows[] = $r; } print json_encode($row ...

Custom AngularJS directive that permits only alphabetic characters, including uppercase letters and the ability to input spaces

I'm currently working on an AngularJS directive that is meant to only allow alphabetical characters, however, I've encountered an issue where it disables caps lock and space functionality. While the main goal is to prevent special characters and ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

Any tips on extracting a primitive data type from a JSON file?

The JSON file retrieved from a GET request is as follows: { "vcalendar": [ { "version": "2.0", "prodid": " CalendarID", "vevent": [ { "uid": " EventID", "dtstamp": "20180725T000000", ...

Slide in the Toggle Effect to Your Navigation Menu

Seeking help with enhancing my jQuery dropdown menu to include a slide down toggle effect similar to this example: http://jsfiddle.net/LaSsr/188/. Any assistance in applying this slide effect to the following JSfiddle would be greatly appreciated. Thank yo ...

Discovering hidden files within appsettings.json in ASP.NET Core 6 using Program.cs

Within Appsettings.json, the code resembles the following: { "Project": { "ConnectionString": "Data Source=(local)\SQLSERVER; Database=MyCompany; Persist Security Info=false; User ID='sa'; Password='sa ...

Is it possible to interpret the camera using radius or diameter instead of the traditional x, y, z coordinates

I've been exploring this scenario where I am trying to figure out if it is possible to move a camera by adjusting the radius and diameter instead of using x, y, z positions (Vectors). Currently, I am working with a cube, but my goal is to introduce a ...

Loop through an array of objects that each contain two sub-objects using ng

I'm looking to organize each data-record in an object that contains two other objects structured like this: data Object { abbData={...}, invoiceData={...}} abbData Object { service="24", conn_fee="0", month_fee="249", more...} invoiceData ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Is it important to minify JavaScript npm packages?

In my journey of creating numerous npm packages, I find myself pondering over the question: "Should JavaScript npm packages be minified?" I have always held the belief that minifying already minified code is not a good practice, which is why I have refrai ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...