Ensure no duplicate values are pushed into array when using angularjs foreach loop

I have a specific array that I am using in my foreach function

  $scope.categoryList =  [
    {
        "id": 44,
        "creationTimestamp": "2019-11-15 17:11:17",
        "name": "FIXED ",
        "description": "FIXED",
        "$$hashKey": "object:108"
    },
    {
        "id": 44,
        "creationTimestamp": "2019-11-15 17:09:32",
        "name": "SAV",
        "description": "SAV",
        "$$hashKey": "object:109"
    },
    {
        "id": 76,
        "creationTimestamp": "2021-08-17 14:19:14",
        "name": "TEST CAT",
        "description": "TEST CAT",
        "$$hashKey": "object:110"
    },
    {
        "id": 77,
        "creationTimestamp": "2021-08-17 14:19:14",
        "name": "TEST CAT",
        "description": "TEST CAT",
        "$$hashKey": "object:110"
    } 
 
]

To extract the IDs from the array above and remove duplicate values before pushing them to a new array, I've written the following code:

   angular.forEach($scope.categoryList, function (object) {
                    $scope.myNewarray.push(object.id);
                });

The resulting new array should contain unique ID values like this:

$scope.myNewarray = [44,76,77]

I want only the unique IDs to be present in my new array.

Answer №1

To extract unique values from an array, you can leverage the Set method in JavaScript.

$scope.categoryList = [
  {
    id: 44,
    creationTimestamp: "2019-11-15 17:11:17",
    name: "FIXED ",
    description: "FIXED",
    $$hashKey: "object:108",
  },
  {
    id: 44,
    creationTimestamp: "2019-11-15 17:09:32",
    name: "SAV",
    description: "SAV",
    $$hashKey: "object:109",
  },
  {
    id: 76,
    creationTimestamp: "2021-08-17 14:19:14",
    name: "TEST CAT",
    description: "TEST CAT",
    $$hashKey: "object:110",
  },
  {
    id: 77,
    creationTimestamp: "2021-08-17 14:19:14",
    name: "TEST CAT",
    description: "TEST CAT",
    $$hashKey: "object:110",
  },
];

$scope.myNewarray = [...new Set($scope.categoryList.map((o) => o.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

Switch the class of the parent div when clicked (or when ng-clicked)

I am attempting to create collapsible panels with a resize button by incorporating the following JavaScript code: function toggleSize() { $(".elementGraphic").click(function () { $(this).toggleClass("col-md-12"); $(this).toggleClass("c ...

Detecting the click area within a window using JavaScript to automatically close an element

Hello everyone, I am currently working on implementing a JavaScript code that is commonly used to detect click areas for closing an element such as a side navigation or a floating division when the user clicks outside of the element. The functionality wo ...

What is the best way to retrieve the previously chosen item from an array?

I have successfully implemented dynamic pill tabs with one minor issue remaining. The most crucial aspect is that when I remove a pill, I want it to return to the previously opened tab. I have provided a StackBlitz example without routes on this page: -> ...

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Angular 8 directive for concealing phone numbers

I am currently facing an issue with my phone mask directive that is designed to accept US format phone numbers. The problem arises when I try to clear the input by deleting one character at a time using the backspace key, as the value in the input field do ...

Obtaining input value from a JavaScript function

Using the highcharts 4 JavaScript library allows for customizing chart buttons. Check out a chart with custom buttons To customize buttons in highcharts, you can push button objects into an array and include this array in the Highcharts configuration. H ...

Encountering a problem when using the routingService to navigate inside a JavaScript function

Within my Angular component, I have a method called onCellPrepared. In this method, I am using jQuery to attach a span tag. I want to be able to trigger an Angular service to navigate to another page when the span tag is clicked. How can I successful ...

How much time can the browser dedicate to running JavaScript before moving on to loading a new page?

The webpage contains multiple hyperlinks. I want to monitor user clicks on these links. Whenever a user clicks on a link, an Ajax request is sent to my server for processing. The server then returns relevant data, which is further processed on the client ...

The `forEach` method cannot be called on an undefined node.js

I have been developing a small study website but encountered an issue with the title. Despite extensive internet research, I have not been able to find a solution. The system I am using is Ubuntu with node.js, express, and mysql. app.js var fs = requir ...

Fixed navbar at the bottom of the page that transitions to static when scrolling reaches a certain location

Is it feasible to achieve this using Bootstrap v3? After conducting extensive research, it appears that a custom solution may be necessary. In essence, I am working with a navbar positioned at the bottom of the content area. Upon page load, if the navbar& ...

"Troubleshooting the inconsistency of GraphQL resolver context functionality between Playground and the client in the official NextJS starter

Currently, I am making adjustments to my NextJS/Apollo application to enable SSG with GraphQL API routes. I have referenced this official NextJS starter example as a foundation for configuring the client. An issue arose in my application which led me to g ...

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Use jQuery to display the first 5 rows of a table

I recently posted a query on show hide jquery table rows for imported xml data regarding how to toggle visibility of specific table rows using jQuery. Now, I am seeking advice on how to make the first 5 elements always visible within the same context. Belo ...

Issue with React iframe YouTube: Object.defineProperty being invoked on a non-object

I successfully created a component for embedding YouTube videos in my React app and it's working perfectly. My implementation involves using an iframe. <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-res ...

Fill in a dropdown using the options selected from another dropdown menu

I have developed the following code snippet: User: <select id="sel_depart"> <option value="0">All users</option> <?php $all_users = User::getUsersAdmin(); foreach($all_users as $value){ ?> <option value="<?php ...

Difficulty encountered while connecting JSON data to a list using Angular JS

Currently, I am working on developing an application using AngularJS. In this project, I need to populate the customer list using data from a database. To achieve this, I have written a web method to retrieve the necessary data: [WebMethod] [ScriptMet ...

"Exploring the possibilities of Social Login integration with Ionic using Firebase V3

Struggling to implement a simple social login feature (like Google, Facebook, etc.) in an Ionic App using Firebase V3 as the backend. Unfortunately, all the tutorials and examples found online seem to be outdated and do not work with the new API v3. For i ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

Verify that the value being returned is in the form of a promise

Provided an angular controller containing the following function: this.checkResponse = function (response) { if (response.success === true) { return $q.resolve(response); } else { return $q.reject(response); } }; I am looking to test with J ...