Organize values according to property values and display them using JavaScript

I have a unique array structure that is as follows:

var array = [[
    { "location": {} },
    { "distance": 6.4 },
    { "zip1": "06120" },
    { "zip2": "06095" },
    { "group": 1 },
    { "weight": 1119 }
], [
    { "location": {} },
    { "distance": 6.41 },
    { "zip1": "06095" },
    { "zip2": "06120" },
    { "group": 2 },
    { "weight": 41976 }
], [
    { "location": {} },
    { "distance": 6.41 },
    { "zip1": "06095" },
    { "zip2": "06120" },
    { "group": 1 },
    { "weight": 41976 }
]];

My goal is to access the values in the array based on specific property values and display them in HTML format. The expected output should be segmented into separate arrays according to their "group" property. Below is an example of how I want the data to be presented:

group 1:
  - list of all zip1's under group 1
group 2:
  - list of all zip1's under group 2 

I attempted to achieve this using a loop but unfortunately, I couldn't obtain the desired result:

for (var k = 0; k < array.length; k++) {
    var currentArray = array[k];    
    if (flag[currentArray[2]["zip1"]]) continue;
    flag[currentArray[2]["zip1"]] = true;
    finalOutput.push(currentArray);
}

I need assistance in splitting the array and displaying it in an HTML format organized by groups.

https://i.sstatic.net/bAmGr.png

Answer №1

Utilizing the power of reduce, you can structure an object in such a way that each unique group value serves as the key, while an array consisting of corresponding zip1 values is stored as the associated data:

Subsequently, iterate through the Object.entries method to dynamically generate the HTML elements:

const array = [[{"loc":{}},{"distance":6.4},{"zip1":"06120"},{"zip2":"06095"},{"group":1},{"weight":1119}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":2},{"weight":41976}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":1},{"weight":41976}]];

const merged = array.reduce((r, a) =>{
  const { group } = a.find(n => n.group)
  const { zip1 } = a.find(n => n.zip1)
  r[group] = r[group] || []
  r[group].push(zip1)
  return r;
},{})

const output = document.getElementById('output');

Object.entries(merged).forEach(([group, zips]) => {
  const h1 = document.createElement('h1');
  h1.innerHTML = "Group: " + group
  
  const span = document.createElement('span');
  span.innerHTML = `Zip Codes - ${zips.join(', ')} (in Group - ${group})`;
  
  output.appendChild(h1)
  output.appendChild(span)
})
<div id="output"></div>

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

Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue. Take a look at the screenshot and code snippet provided: function myF ...

What is the best way to ensure that the user interface stays updated with alterations made to

I am currently studying various front end design patterns, and I repeatedly come across the idea of implementing a virtual shopping cart in a shopping cart scenario. The suggestion is to have the user interface actively monitor any changes to the cart and ...

What specific method of sorting does this code utilize?

Here's a JavaScript code snippet that sorts an array of n numbers in ascending order. I've used this code in several interviews, but I'm still unsure about which sorting algorithm it represents. let arr = [7, 9, 2, 11, 5] for (let i = 0; i ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

How can CKEditor ensure that there is a paragraph tag within a div element?

Working on my current CMS, I have the need to include some custom HTML (which is functioning as expected): var element = CKEDITOR.dom.element.createFromHtml("<div class='sidebar'>Edit Sidebar Text</div>"); The issue arises when atte ...

Redirecting to another page with a simple link is not recommended

Once the user successfully logs in, I redirect them to the dashboard. Everything was working fine until I deployed it using tomcat. Now the URL is http://localhost:8080/myWar/ So when I use this: window.location.href = "/dashboard"; it redirects to ht ...

Slider buttons are not appearing in Time Picker

I recently added a Time Picker to my project, but I'm experiencing an issue where the slider buttons for selecting time are not showing up. Could you please refer to this image: Checking the console, there don't seem to be any errors present. ...

Altering the color upon repetition and utilizing JQuery coordinates for the dynamic movement of elements

I've been working on recreating some JQuery tutorials by myself, but I've hit a roadblock. My goal is to create an object that moves from one position to another while changing color when it repeats. I attempted to achieve this by using an array ...

Searching for a way to obtain the iterator index/key in protractor along with angular?

Is there a method to retrieve the iterator index/key while searching for elements by repeater? protractor.By.repeater("(id,cat) in pets") In this particular scenario, I am aiming to acquire the "id" of the cat. The "id" is not displayed as one of the col ...

Searching for boolean values within an array field

I am facing a unique challenge when it comes to querying a boolean field and a string field nested within an array field. The index mapping is structured as follows: indexes :string_field_1, type: 'string' indexes :string_field_2, type: 'st ...

Ways to retrieve a variable from an EJS file using a separate JS file

I am currently developing a straightforward web application that receives 3 different types of inputs and then displays one of 3 distinct EJS files from a views directory (using Node and Express). Each of these rendered EJS files requires the content of a ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

The "truth" parameter within the xmlHttpRequest .open() function

After referencing MDN, it mentioned that by default, the JavaScript function will keep running until the server response is received. This is essentially what AJAX is all about - Asynchronous JavaScript and XML. Even though I have some experience with A ...

Retrieving reduced or corresponding items from a JSON document

My JSON data is structured as follows: [ { "id" : "1", "type" : "hardware" }, { "id" : "2", "type" : "software" } ] When I execute the following code: $http({ method: 'get', url ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach: angular.module('myapp',[]),directive('mydirective', function() { var directive = {}; directive.restrict = 'E'; directi ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Exploring Ruby array functions and their results

My task is to develop a code that takes a number as input and returns all the even numbers between 1 and the input number. These numbers are then printed in a specific format as shown below: 22 4444 666666 etc... Below is the code that I have written so ...