Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question.

My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's.

Let's consider some case scenarios:

  1. Two different ids have entries for "GOOGLE" - Valid Case
  2. Two different ids have entries for "FACEBOOK" - Valid Case
  3. An entry for "TWITTER" doesn't match any other id - INVALID Case.

In this specific scenario, I need help removing the data related to case 3.

 {
  "id" : 378,
  "code" : "TWITTER",
  "comment" : "zeeer"
}

Any assistance or input on solving this problem would be greatly appreciated.

****Below is the original array data****

 data = [ {
  "id" : 381,
  "code" : "GOOGLE",
  "comment" : "ffff"
}, {
  "id" : 381,
  "code" : "FACEBOOK",
  "comment" : "fff"
}, {
  "id" : 378,
  "code" : "TWITTER",
  "comment" : "zeeer"
}, {
  "id" : 378,
  "code" : "GOOGLE",
  "comment" : "rferer"
}, {
  "id" : 378,
  "code" : "FACEBOOK",
  "comment" : "fefehh"
} ]

I've attempted a solution below, but I'm uncertain about the next steps.

Furthermore, the framework I am using is Angular 7, so solutions tailored to typescript would be most beneficial.

this.data.forEach((row, index) => {
        let value = row.id;
        if(originalArray.indexOf(value) == -1) {
          console.log(value);
        }
        originalArray.push(row);
     })

Answer №1

Give this a shot:

 data = [ {
  "id" : 381,
  "code" : "GOOGLE",
  "comment" : "ffff"
}, {
  "id" : 381,
  "code" : "FACEBOOK",
  "comment" : "fff"
}, {
  "id" : 378,
  "code" : "TWITTER",
  "comment" : "zeeer"
}, {
  "id" : 378,
  "code" : "GOOGLE",
  "comment" : "rferer"
}, {
  "id" : 378,
  "code" : "FACEBOOK",
  "comment" : "fefehh"
} ]

var result = data.reduce((unique, o) => {
    if(data.filter(obj => obj.id != o.id && obj.code === o.code).length>=1) {
      unique.push(o);
    }
    return unique;
},[]);

console.log(result);

Answer №2

Your statement that "Any code + Id pair that is not matched is removed" appears to conflict with the first two scenarios because those pairs are not matched due to different IDs.

However, the provided code will only retain items that share the same code but have different IDs.

const data = [ { "id" : 381, "code" : "GOOGLE", "comment" : "ffff" }, { "id" : 381, "code" : "FACEBOOK", "comment" : "fff" }, { "id" : 378, "code" : "TWITTER", "comment" : "zeeer" }, { "id" : 378, "code" : "GOOGLE", "comment" : "rferer" }, { "id" : 378, "code" : "FACEBOOK", "comment" : "fefehh" } ];
let result = data.filter(({id,code}) => !!data.find(obj => obj.code === code && obj.id !== id));
console.log(result);

Ideally, a lookup or hashmap would be more efficient than nested array methods in this scenario to avoid unnecessary iterations. However, since you have already accepted an answer, I will refrain from implementing that approach at this time.

Answer №3

Using Lodash Library

const info = [ {
      "id" : 381,
      "code" : "GOOGLE",
      "comment" : "ffff"
    }, {
      "id" : 381,
      "code" : "FACEBOOK",
      "comment" : "fff"
    }, {
      "id" : 378,
      "code" : "TWITTER",
      "comment" : "zeeer"
    }, {
      "id" : 378,
      "code" : "GOOGLE",
      "comment" : "rferer"
    }, {
      "id" : 378,
      "code" : "FACEBOOK",
      "comment" : "fefehh"
    } ];

    const groupedInfo = _.groupBy(info, 'code'); // remember to import * as _ from 'lodash'

    console.log(info.filter(data => groupedInfo[data.code].length > 1));

Output:

[Object, Object, Object, Object]
0: Object
code: "GOOGLE"
comment: "ffff"
id: 381
__proto__: Object
1: Object
code: "FACEBOOK"
comment: "fff"
id: 381
__proto__: Object
2: Object
code: "GOOGLE"
comment: "rferer"
id: 378
__proto__: Object
3: Object
code: "FACEBOOK"
comment: "fefehh"
id: 378
__proto__: Object

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

How to retrieve JSON data from a node.js server and display it in HTML

Attempting to develop a web app featuring drop-down menus that display data from a SQL server database. After researching, I discovered how to utilize Node.js to output table data in the command prompt. var sql = require('mssql/msnodesqlv8'); ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Utilize React to iterate through data retrieved from firebase

I'm currently facing an issue with Google Firebase Realtime database where I am unable to create an array of the collection. Whenever I loop through the const return in console log, I receive messages as individual objects. However, what I actually n ...

Creating experiences for websites controlled by gestures

It's been a great experience working on a website that utilizes gesture-based technology. My inspiration for this project came from various sources, including this link. Despite researching extensively through websites, Google, Wikipedia, and GitHub, ...

Flatten information from an object containing multiple objects within an array

In my current project using Vue, I am making an API call to retrieve data from my Laravel backend (nova). The returned data is structured in the following way. The data consists of an array, which contains arrays of objects. Each array represents a record ...

Errors related to TypeScript syntax have been detected within the node_modules/discord.js/typings/index.d.ts file for Discord.JS

I keep encountering typescript syntax errors after pulling from my git repository, updating all npm modules on the server, and running the start script. The errors persist even when using npm run dev or npx tsc. I've attempted the following troublesh ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Issues with Socket.io in receiving messages on the client side

I've been experimenting with websocket testing in Angular and Nestjs by following this tutorial. This is the gateway component from my Nestjs project. import { SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, MessageBody } f ...

Problem with Packaging Angular and Spring Boot Applications

My current project structure consists of a spring boot angular project +--app-ui |--+--src |--+--dist |--app-backend |--+--src |--+--+--main |--+--+--+--resources |--+--+--+--+--static |--+--+--+--java The app-ui directory contains the Angular 6 code, wh ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

There are two modals present on the page, however only one of them is triggered for all actions in Angular 2

I'm encountering an issue with my page where I have set up two confirmation modals - one for resetting a form and another for deleting an item. Strangely, only the reset modal is being triggered for both actions and I can't figure out why. Could ...

The solution to resolving setState not updating within a react context

I am encountering a problem where my context does not seem to update when I attempt to modify it using a react hook. The code snippet is provided below, and I have a feeling that I might be overlooking something minor. appContext.tsx import React, { use ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Once the <a> element is clicked, ensure that the function finishes executing before attempting to click/process it again

Utilizing jQuery.get for AJAX requests, I trigger a server request when the user clicks on the <a> element. The response is then used to update the content within the <div id='aaa'>. However, if the user clicks on the <a> rapid ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

How to access webpack's require.context feature on the development server

In my webpack development configuration, I have set up a mocked backend using Express. Following an example from the DevServer Docs, my setup looks something like this: module.exports = { // ... devServer: { setupMiddlewares: (middlewares, devServe ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

Obtain the Week Input's Value

Is there a way to store the value of a week input in a variable and then display it in a span? I attempted the following code: <input type="week" name="week" id="week-selector"> <span id="kalenderwoche"> ...

Ways of accessing an array within an if statement

I have a dashboard with admin privileges for my application. In this dashboard, the admin can select a user from a dropdown list. Once a user is selected, I make an AJAX call to retrieve the user's data and store it in a variable named $result. Howeve ...