Is the value of the object in the array already present in another array of objects?

Plunker - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp

In my angular project, I am working on a view that displays a list of users in the main container (array-A) and a sidebar with selected users (array-B).

The first array (A) contains all users:

[{ $$hashKey: "00F", id: "118207f5e52c3eb619a8760bc08c8224", username: "John Smith" }, { $$hashKey: "00G", id: "9c2d6f31c88e7a654e64bd0d3371360a", username: "Fredy Rincon" }, { ... }]

The second array (B) holds the users already selected from Firebase database to pre-populate the sidebar. These users should appear exactly like they do in array-A.

My objective is to allow adding and removing objects from array-B/sidebar by clicking on items in array-A/main container.

I have attempted a solution but it only adds and removes items without considering the existing pre-populated users on the sidebar.

To illustrate:

$scope.selectedUsers = array-B

user = object in array-A

$scope.selectUser = function (user) {
  console.log($scope.selectedUsers.indexOf(user))
  if ($scope.selectedUsers.indexOf(user) === -1 ) {
    $scope.selectedUsers.push(user);
    console.log($scope.selectedUsers);
  } else {
    $scope.selectedUsers.splice($scope.selectedUsers.indexOf(user), 1);
    console.log($scope.selectedUsers);
  }
};

I'm unsure how to solve this issue and would appreciate any assistance. Thank you.

Thanks.

Answer №1

Utilize Array.prototype.reduce method for user validation before addition:

$scope.add = function(user){
  var match = $scope.selectedUsers.reduce(function(prev, curr) {
    return (user.id === curr.id) || prev;
  }, false);
  console.log(match ? 'match' : 'no match');
  if (!match) $scope.selectedUsers.push(user);
};

... where your template includes:

<p ng-repeat="user in users">{{user.username}} <a ng-click="add(user)">+</a></p>

To eliminate users from the selectedUsers array, use Array.prototype.splice method:

$scope.remove = function(index){
  $scope.selectedUsers.splice(index, 1)
}

...where your view is structured as follows:

<p ng-repeat="selectedUser in selectedUsers">{{selectedUser.username}}
<a ng-click="remove($index)">--</a></p>

View Working Example on Plunker

Answer №2

To efficiently manage your objects with unique string IDs, consider storing just the IDs in two separate arrays (array-A and array-B) and keeping a dictionary of the complete data objects in a central service. You can then utilize an angular filter to retrieve the required full data object by its ID for various purposes such as presentation.

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

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Iview Table UI Cell

Is there a way to retrieve the cell data from a library iview table in Vue.js upon clicking? I am looking to capture both the value of the cell and the title of the column, and then modify the CSS of that particular cell. For instance, clicking on one ce ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Inquiry regarding the ng-disabled directive in AngularJS

<div ng-app="myApp" ng-controller="myCtrl"> <button type="submit" class="btn btn-primary pull-left" ng- disabled="captchaError">Submit</button> </div> <script> var app = angular.module('myApp', []); app.controller( ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

.fetchevery(...).then has no function

I recently upgraded Angular to version 1.6.4. As a result, I made changes to the code by replacing .success and .error with .then However, now I am encountering the following error: An unexpected TypeError occurred: .getAll(...).then is not a function ...

Retrieving the last entity of a $resource in AngularJS using a controller

How can I access the last entity of a REST resource from within the controller? I have a factory that returns a $resource: angular.module('foo', ['ngResource']). factory('Api', ['$resource', function($resource) ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

ng-repeat on a transcluded directive fails to show the properties of the object

Having trouble with menu directives. The bottom three menu items work fine, but the ones generated by an ng-repeat are missing attributes like route, icon, and label when I run the code. The ng-repeat seems to be creating the correct number of menu-items, ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

There was an error in Index.js: The UserForm component did not return anything from the render function. This typically occurs when a return statement is missing. To render nothing, you can return

Hello, I'm a beginner with React and I'm attempting to add a row in my React app when a button is clicked. I referenced this guide on how to dynamically add and remove table rows in React.js However, I'm having trouble adapting it to my cod ...

Retrieve a specific item from a JSON response using Node.js

When I receive a message from a WebSocket, the code snippet is triggered like this: ws.onmessage = (e) => { debugger if (e.data.startsWith('MESSAGE')) alert(JSON.stringify(e.data)) ImageReceived(e.data) c ...

Tips for ensuring a controller function only runs once in AngularJS

I have a controller that is being referenced in some HTML. The HTML changes on certain events, causing the controller function code to execute multiple times. The issue lies in a portion of the code that should only be executed once. Shown below is the ...

Apply a class to the input element within an ng input tag

When working with ng-input-tag, I tried to apply a bootstrap class to the input element of HTML in order to utilize specific bootstrap styles. Unfortunately, it did not work as expected. Below you can find the code snippet: angular .module('m ...

Utilizing AngularJS: Accessing the parent controller from a child component using the controllerAs syntax

Looking to access a function from the parent controller within my directive using the controllerAs notation in Angular 1.3.14. Here is the structure: Controller (with save function) (Child) controller Directive with a template (and isolated scope). Ins ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...