Creating an original list by iterating through a given list

I understand that some may consider this a duplicate, but I have yet to come across a similar example that I can relate to with my limited knowledge. So, I apologize in advance :)

This should be pretty simple for an experienced JS developer, I assume.

My struggle lies in trying to match on an array's property:

if (!uniqueEnts.includes(ent.entity)) {  // how do I match on uniqueEnts.entityName ?

The current approach is yielding too many results in the new list, and the check above doesn't provide the correct comparison against uniqueEnts.entityName.

JSON Input : https://i.sstatic.net/qSHAt.png

Desired output: A new list (uniqueEntities) with two properties:

  • entityName (unique)
  • entityColor (randomly generated)

Code:

uniqueEntities() {
        let uniqueEnts = []
        this.nluDataUnfiltered.forEach(function (i) {
            i.entities.forEach(function (ent) {
                if (!uniqueEnts.includes(ent.entity)) {
                    let obj = {
                        entityName: ent.entity,
                        entityColor: Util.getRandomColor()
                    }
                    uniqueEnts.push(obj)
                    obj = null
                }
            })
        })
        return _uniqueEnts.entityName.sort().value()
        // earlier tryout --> return _(uniq(uniqueEnts.entityName)).sort().value()
    },

UPDATED WITH LATEST TRYOUT:

uniqueEntities() {
        let uniqueEntityObj
        var uniqueEntity = Array.from(new Set(data.map(el => this.nluDataUnfiltered.entities[0].entity)));
            uniqueEntityObj = uniqueEntity.map(el => { 
                entityName: el,  
                entityColor: Util.getRandomColor() 
            });
        return uniqueEntityObj
    },

Error: https://i.sstatic.net/YHK6A.png

Answer №1

To find all the distinct entities in your array, one approach is to utilize sets as they can only hold unique values. After extracting these unique entities, you can then use .map once more to transform them into an array of objects.

var rawData = this.dataSetUnfiltered.map(
  (element) => {
    if (element.entities.length == 0)
      return [];

    return element.entities.map(
      (_entity) => {
        return _entity.entity;
      }
    )
  });

var processedData = [].concat.apply([], rawData);
var distinctEntities = Array.from(new Set(processedData));

var entityObjects = distinctEntities.map((element) => {
  return {
    name: element,
    color: Util.getRandomColor()
  };
});

Answer №2

Based on @void's concept of generating a list of unique entities from a Set, the code below accomplishes this using the spread operator and array reduce methods to create an Array of all entities.

let uniqueEntityObj = Array.from(
    new Set(
        nluDataUnfiltered.reduce(
            (accumulator, object) => (
                [...accumulator, ...(object.entities.map(subObject => subObject.entity))]
            ),
            []
        )
    )
).map(entity => ({entityName: entity, entityColor: Util.getRandomColor()}));

For a more concise (albeit less readable) version, see below:

let uniqueEntityObj = Array.from(new Set(nluDataUnfiltered.reduce((acc, obj) => ([...acc, ...(obj.entities.map(sObj => sObj.entity))]), []))).map(ent => ({entityName: ent, entityColor: Util.getRandomColor() }));

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

Fade in and out a Div with a distinct class and ID

I'm currently experiencing a minor issue with some jQuery code. Below are some divs: <div class="add" id="1">Follow</div> <div class="added" id="1">Following</div> <div class="add" id="2">Follow</div> <div clas ...

I am looking for a feature similar to a computed property that allows me to update the data after the initial change

I am facing a situation where I need to update data whenever changes are detected in a state. The user should have the ability to further edit this information within a textarea. Although using computed properties fetches the data exactly as desired, any m ...

Ways to retrieve text files prior to the webpage loading (synchronously)

I have a simple task at hand that I really want to accomplish - loading some glsl fragment shaders from the disk or server, and then initializing a WebGL web page. Web programming is not my forte; I usually prefer working on shaders and OpenGL in C++. If i ...

Fetching chat messages using an AJAX script depending on the timestamp they were sent

I am currently working on developing a real-time chat application with various rooms as part of my project. Progress has been smooth so far, but I am facing an issue with properly fetching the most recent chat messages from the database. The message table ...

Having trouble transmitting a file from the frontend to the server in your MERN project?

Struggling to transfer an image file from the React frontend to the server and encountering issues with sending the file: Below is the front end code snippet: useEffect(()=>{ const getImage=async ()=>{ if(file){ ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

Unable to get Angular ng-click to function properly when used in conjunction with $

I am encountering an issue with triggering a click event in my Angular app using code similar to the example below. Can anyone help me understand why the event is not being triggered? var app = angular.module("myApp", []) app.directive('myTop', ...

dart, setting the root directory for web application

I'm looking to include some sample websites in my web framework package. Currently, the sites work fine when running them as Dart-only implementations, but if I need to compile them to JavaScript, I have to manually move the subfolder from my package& ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

Combining query results/objects by id in an array within a React application with Firebase Firestore

After retrieving chat messages from a Firestore snapshot, I have the following query result involving conversations among three individuals: {timestamp: "October 25th 2020, 11:13:59 am", name: "John Doe", email: "<a href="/cdn ...

Retrieving the present precipitation amount from a Java Script API

I'm having some issues with extracting information from this list because I don't have much experience with JavaScript and APIs. The API I'm working with provides data for the current hour, but I'm struggling to retrieve that specific v ...

What could be causing my newsletter form to malfunction on Amazon CloudFront?

I'm currently working with HTML on an Amazon EC2 instance (Linux free tier). I want to integrate CloudFront into my setup, but I'm encountering issues with my newsletter functionality. Despite not being an expert in AWS, I am struggling to unders ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Making use of JavaScript's XMLHttpRequest() function allows for seamless

My issue revolves around my use of multiple XMLHttpRequest() requests in order to retrieve the value (miniTable) returned by the TableRow() function. Strangely, while I get the desired value when using alert() at the end of the TableRow() function, the T ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

What is the best way to display the time of a post update similar to the style of

I am currently working on creating a notification deck. Instead of displaying the time when a notification was received, I aim to show the time that has passed since its arrival similar to how Twitter and Facebook do it with formats like "32m" or "1 hour a ...