Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {
    var myObjjj = JSON.parse(this.responseText);

    var result = myObjjj.features.filter(c => c.properties.AREAID === "area4").map(res => res.properties.CDNAME + "<br>").sort().join('');
    document.getElementById("list").innerHTML = result;
  }
};
xmlhttp.open("GET", "https://api.npoint.io/eed1932ca3c208946d86", true);
xmlhttp.send();
<html>
<head>
    <title>Read data from External JSON file using JavaScript</title>
</head>
<body>
    <h3>
        Data extracted from External JSON file using JavaScript.
    </h3>
    
        <p id="list" style="border: 2px solid yellow;"></p>
    

</body>
</html>

The JSON data retrieved from the specified URL contains information about different divisions and areas. The objective is to eliminate duplicate values to display only distinct entries, as shown below:

Area No. 13

Center No. 14

Division No. 11

Division No. 13

Division No. 14

Division No. 16

Division No. 17

Division No. 18

Division No. 19

Answer №1

Your code before optimization:

var result = myObjjj.features.filter(c => c.properties.AREAID === "area4").map(res => res.properties.CDNAME + "<br>").sort().join('');

Prior to the .join() operation, duplicates must be handled. Additionally, using .map() to insert <br> is unnecessary as .join() performs this function.

The snippet below utilizes new Set() and Array.from() for duplicate management:

const cdNames = myObjjj.features.filter(
  c => c.properties.AREAID === "area4"
).map(
  res => res.properties.CDNAME
);
const results = Array.from(new Set(cdNames)).sort().join('<br>');
  1. Filter by AREAID
  2. Convert the filtered array to an array of only CDNAMEs.
  3. Transform that array into a set. (Duplicates are eliminated as sets are unordered collections of distinct values. Re-adding an existing value in a set does not impact it.)
  4. Revert the set back to an array.
  5. Sort the array.
  6. Merge the array, with <br> serving as the separator.

Functional demonstration:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    const myObjjj = JSON.parse(this.responseText);

    const cdNames = myObjjj.features.filter(
      c => c.properties.AREAID === 'area4'
    ).map(
      res => res.properties.CDNAME
    );
    const results = Array.from(new Set(cdNames)).sort().join('<br>');

    document.getElementById("list").innerHTML = results;
  }
};
xmlhttp.open("GET", "https://api.npoint.io/eed1932ca3c208946d86", true);
xmlhttp.send();
<html>
<head>
    <title>Fetch data from External JSON file using JavaScript</title>
</head>
<body>
    <h3>
        Data extracted from External JSON file utilizing JavaScript.
    </h3>
        <p id="list" style="border: 2px solid yellow;"></p>
</body>
</html>

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

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Exploring the Fundamentals of XSS

Currently, my technology stack consists of Symfony2, Twig, and Doctrine. When it comes to securing my website, I am particularly concerned about preventing XSS attacks. However, despite taking precautions, I'm not sure what more I can do. Persisten ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

What is the method for displaying the delete icon, a child component located within the Menu Item, upon hovering over it using Material UI CSS syntax?

My goal is to display the delete icon when hovering over a specific menu item that is being mapped using the map function. The desired functionality is for the delete icon to appear on the corresponding menu item when it is hovered over. I attempted to i ...

Encountering a problem with loading ajax data in jVectorMap

I'm currently facing an issue where I am unable to load data from visitors into a map created using the jvectormap plugin. This problem is really frustrating me as I can't seem to fetch the data through ajax, although it works fine when I input ...

Having trouble loading my array from JSON into the UITableView

The .h file includes @interface HomeTVC : UITableViewController @property (nonatomic, strong) NSArray *spotTitle; while the .m file contains #import "HomeTVC.h" @interface HomeTVC () @end @implementation HomeTVC - (id)initWithStyle:(UITableViewStyl ...

Submitting data from a JavaScript frontend to a PHP backend

I've exhausted all options in attempting to resolve this issue. The javascript code is designed to send a list of product IDs to a PHP page. When products are selected, the submit button should activate the submit function. function submit() { ...

Statistics Sweden SCB API call was made, but unfortunately, no data was retrieved

I am having trouble accessing the actual values of the data in my table, as all I can see is the dates in the JSON output generated. The specific link I am using is: "http://api.scb.se/OV0104/v1/doris/en/ssd/START/FM/FM5001/FM5001A/FM5001SDDSPM" ...

Failure to trigger the success action in ExtJS

I am currently utilizing struts2 for the server-side implementation combined with ExtJS4 for the user interface. I have a basic form that I submit to the server, but the response consistently goes to the failure case of the request even though I am just re ...

Utilizing jQuery and AJAX for submitting multiple POST requests

Experiencing a problem with posting data via AJAX using a drag and drop interface. The data is being sent to the POST URL as intended, but there's a recurring issue where the POST request occurs twice, causing the processing URL to handle the data aga ...

How can I prevent the substitution of "&" with ""&amp;" when using PHP's include function?

$mRef = $payment[ID]; $sign = $mCode.$mRef.$secureKey; $sign = hash('sha256', $sign); $link = ("https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?merchantCode=".($mCode)."&merchantRefNumber=".($mRef)."&si ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Entering a value into an HTML textbox using Awesomium in VB.NET

This code snippet is used to split text from a listbox: For Each Item As Object In ListBox1.SelectedItems TextBox2.AppendText(Item.ToString + Environment.NewLine) Next Dim str As String = TextBox2.Text D ...

Using Javascript to make a call to a RESTful endpoint

My current challenge involves attempting to make a call to the Spotify API from JavaScript: function callAPI() { var xhttp = new XMLHttpRequest(); xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track'); ...

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...