The intricate process of selecting and organizing data into a structured

In my code, there is an array called listSelected that gets updated after each selection in another grid.

const listSelected =    
 [{    
    "_id": "10",    
    "age": 35,    
    "name": "Paige Zamora",    
    "gender": "female",    
    "company": "AUTOMON",    
    "**reference_id": "12**"    
  },    
  {    
    "_id": "11",    
    "age": 40,    
    "name": "Jennifer Carr",    
    "gender": "female",    
    "company": "SYNKGEN",    
    "**reference_id": "11**"    
  }];  

The goal is to cross-reference the values of reference_id with another table named data. If a matching value exists, we extract the corresponding id into a new array. This operation should be done even if the same reference_id appears multiple times.

const data = [{    
    "_id": "**10**",    
    "age": 35,    
    "name": "Paige Zamora",    
    "gender": "female",    
    "company": "AUTOMON",    
    "**reference_id": "12**"    
  },
  ...
];

The final result will be displayed as:

const newGrid = [11,12]

I am considering using nested functions utilizing forEach loops to achieve this, like so:

const newGrid = [];

listSelected.forEach((elt) => {
  data.forEach((item) => {
    if (item.reference_id === elt.reference_id) {
       newGrid.push(item.id);
       newGrid = Array.from(new Set(newGrid));
     }
   });
});

Are there any alternative approaches to simplify this function and avoid using nested forEach loops?

Answer №1

To create a "reverse-unique" array, consider the following approach:

const listSelected = [
  { "_id": "10", "age": 35, "name": "Paige Zamora", "gender": "female", "company": "AUTOMON", "reference_id": "12" }, 
  { "_id": "11", "age": 40, "name": "Jennifer Carr", "gender": "female", "company": "SYNKGEN", "reference_id": "11" }
];

const data = [
  { "_id": "10", "age": 35, "name": "Paige Zamora", "gender": "female", "company": "AUTOMON", "reference_id": "12" }, 
  { "_id": "11", "age": 40, "name": "Jennifer Carr", "gender": "female", "company": "SYNKGEN", "reference_id": "11" }, 
  { "_id": "12", "age": 38, "name": "Weaver Rosales", "gender": "male", "company": "ETERNIS", "reference_id": "12" }, 
  { "_id": "13", "age": 31, "name": "Myers Pickett", "gender": "male", "company": "ETERNIS", "reference_id": "13" }, 
  { "_id": "14", "age": 36, "name": "Dona Nicholson", "gender": "female", "company": "ETERNIS", "reference_id": "14" }, 
  { "_id": "15", "age": 21, "name": "Niki Blur", "gender": "female", "company": "AUTOMON", "reference_id": "15" }, 
  { "_id": "16", "age": 37, "name": "Bod Dennart", "gender": "male", "company": "SYNKGEN", "reference_id": "16" }, 
  { "_id": "17", "age": 26, "name": "Richard Nelson", "gender": "male", "company": "ETERNIS", "reference_id": "17" }, 
  { "_id": "12", "age": 45, "name": "Pedro Kluivert", "gender": "female", "company": "SYNKGEN", "reference_id": "18" }
];

const merged = [
  ...listSelected.map(item => item.reference_id),
  ...data.map(item => item.reference_id)
];

const reverseUnique = merged.filter((item, index, array) => array.indexOf(item) === index && array.lastIndexOf(item) !== index);

console.log(reverseUnique);

This method optimizes processing by avoiding nested loops that other methods might require.

It starts by combining the two arrays into one and focuses on using only the reference ID for comparison.

Utilizing the concept of opposite unique filtering, this approach effectively identifies duplicate elements in the merged array.

Answer №2

const updatedList = listSeleced.map(listItem => {
    if (data.some(dataItem => dataItem.item.reference_id === listItem.item.reference_id) {
        return listItem.reference_id;
    }
    return;
});

This code hasn't been tested yet, but it is expected to function properly. Another alternative could be using the reduce method.

Answer №3

To implement this functionality, utilize the find method within an array as shown below:

newGrid = [];

listSelected.forEach((elem) => {

    newGrid.push(data.find(function search(item) {

        return item.reference_id === elt.reference_id;

    }).reference_id);
});

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

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

One way to update the value of the current array or object using ngModel in Angular 2 is to directly

I have a situation where I am dealing with both an array and an object. The array is populated with data retrieved from a service, while the object contains the first element of that array. feesEntries: Array<any> = []; selectedFeesEntry: any; clien ...

Prevent data loss on webpage refresh by using Angular's local storage feature

As a beginner in Angular, I am exploring ways to retain user input and interactions on my webpage even after a refresh. After some research, I came across using local storage as a viable solution. A different answer suggested utilizing the following code s ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Encountering the "Not all code paths return a value" TypeScript error when attempting to manipulate a response before returning it, however, returning the response directly works without any issues

Encountering an issue where manipulating/process response and return triggers an error in TypeScript with the message "Not all code paths return a value.". Data is fetched from a backend API using RxJS lastValueFrom operator, along with lodash functions as ...

Having trouble performing nested queries with RxJS 6 and the expand operator in Angular, Firebase, and Observables?

I came across a query on Stack Overflow that helped me fetch a random item from a Firebase collection in my Angular 9 app using AngularFire. While the solution works perfectly and gives me the desired output most of the time, there's an issue when th ...

Error message in React: "The type 'Window & typeof globalThis' does not have a property named 'ethereum'"

Encountering a problem: Issue with 'ethereum' property on type 'Window & typeof globalThis' In my React project, I'm facing an error. The following code is causing the problem: import { ethers } from 'ethers' cons ...

There is no mistake when using a value that falls outside of a TypeScript

Expecting to encounter a compile time error with this code, but it seems my understanding of enums is off... enum SortDirection { ascending = 1, descending = -1 } type IndexSpec = {[index: string]: SortDirection}; var i: IndexSpec = {thing: 3}; ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Are generic constraints leading to type inference selecting the incorrect candidate?

TypeScript Version: 2.6.0-dev.20170826 and 2.4.2 I'm questioning whether I've encountered a TypeScript inference bug or limitation, or if my code is simply incorrect. If the code is valid and it's an issue with type inference, I will repor ...

Jodit-React: Addressing the Placeholder Problem

I've recently incorporated Jodit-react into my react-typescript project, but I encountered an error when adding the config property. The error message stated that it "Has no property common with type." Unfortunately, I'm unsure why this is happe ...

Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options. Below is the code snippet used for the select drop down: < ...

Enhance your Angular component by integrating property bindings and events with transcluded elements

I have an Angular component that includes an <input/> element with property bindings and an event listener. I am exploring the option of allowing users of the component to define a custom input field, potentially with parent elements, through transcl ...

The ts-mocha test does not play well with the use of node-fetch library

I have set up ts-mocha and node-fetch to run a unit test, but I am encountering the following error: TypeError: Unknown file extension ".ts" for ... The content of the file is as follows: import fetch from 'node-fetch'; export defau ...

The program encountered an issue with determining the length of this.slides. The property 'length' is undefined and cannot be

console.log(this.slides.length()); displays Cannot read property 'length' of undefined. After a setTimeout of 100 milliseconds, this message will appear. Is there a way to determine if a child component has finished loading from the parent compo ...

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Angular 6 is throwing an error stating that the element 'app-action-button' is not recognized

I'm facing an issue while trying to incorporate a component that is shared between modules. Unfortunately, all my attempts have resulted in the same error. Despite searching for solutions in similar questions, I have been unable to resolve this error ...

Transforming the express app object into a data type instead of a regular variable

Currently, I am setting up my own TypeScript Express project and aiming to abstract the code for better organization. In my app.ts file, the code looks like this: import express from 'express' const app = express(); const port = 3000; require( ...

JavaScript: Organizing values based on their case sensitivity

Imagine a scenario where we have models ABC23x, ABC23X & abc23X all referring to the same model. These model names are retrieved from API endpoints. Now the UI has two tasks: Display only one model name (ABC23X) When calling the REST API, we need to sen ...