AngularJs array mapping is a powerful feature that allows you to

I am dealing with two arrays

$scope.tags =  [{ "id": 1, "name": "python" }, { "id": 2, "name": "NodeJs" }, { "id": 3, "name": "git" }]

The second array is

$scope.skillsInterested = [1,2];

What I am trying to achieve is:

How do I match the IDs in$scope.skillsInterested array with the first array and print only their names?

I want to display names from the first array for the IDs present in the second.

After receiving multiple suggestions, here's what I attempted:

var tag_map = {};
for (var x = 0; x < $scope.tags.length; x++) {
tag_map[$scope.tags[x]['id']] = $scope.tags[x]['name'];
}
$scope.skillsInts = $scope.skillsInterested.map(function(x) {
return tag_map[x]

When I use console.log

console.log("Result", tag_map);

Sometimes it returns a result, but other times it shows 'map' of undefined.

TypeError: Cannot read property 'map' of undefined
at controllers.js:141
at angular.js:16383
at m.$eval (angular.js:17682)
at m.$digest (angular.js:17495)
at m.$apply (angular.js:17790)
at l (angular.js:11831)
at J (angular.js:12033)
at XMLHttpRequest.t.onload (angular.js:11966)

Thank you in advance.

Answer №1

Create a visual representation of your data in the form of a map that resembles the example below:

var tagMap = { 1: "JavaScript", 2: "React" /* etc. */ };

To achieve this, iterate through your tags and add a new property to an object. Utilize the reduce method to accomplish this task without the need for additional variables.

You can then retrieve names from the newly created object using the notation []: tagMap[1] will yield "JavaScript".

var tags =  [{ "id": 1, "name": "JavaScript" }, { "id": 2, "name": "React" }, { "id": 3, "name": "Vue" }]
var selectedTags = [1,2];
// Generate a mapping for `id: name`
var tagMap = tags.reduce(function(map, tag) {
  map[tag.id] = tag.name;
  return map;
}, {});

// Easily fetch names from the map:
var selectedNames = selectedTags.map(function(id) {
  return tagMap[id];
});

console.log(selectedNames);

By adopting this approach, you reduce the number of iterations over your data. The creation of the map only iterates over the tags list once. Similarly, creating the array with names only loops over the selected tags list once. Therefore, the total "loop count" is roughly

tags.length + selectedTags.length
. In contrast, if you were to use an indexOf-based method, the loop count would be
tags.length * selectedTags.length
.

Answer №2

To efficiently extract data, utilize the filter function on the array labeled first, then verify the existence of the ids before using the map function to retrieve the names.

var first = [{ "id": 1, "name": "javascript" }, { "id": 2, "name": "React" }, { "id": 3, "name": "HTML" }];

var selectedExpTags = [1,2];

var names = first.filter(item => selectedExpTags.some(id => item.id === id)).map(item => item.name);

console.log(names);

Answer №3

To retrieve a list of all names from the $scope.selectedExpTags array, you can iterate over it using a loop. If you are only interested in the first value, you can utilize the array.find method.

Example

var first = [
  { "id": 1, "name": "python" }, 
  { "id": 2, "name": "NodeJs" }, 
  { "id": 3, "name": "git" }];

var selectedExpTags = [1,2];
var names = selectedExpTags.map(x=> first.find( y=> y.id === x ).name )

console.log(names);

Answer №4

const freshArr = []; // Create a new array for manipulation purposes
angular.forEach($scope.tags, function(tag){
$scope.selectedExpTags.forEach(function(selectedTag){ 
    if(selectedTag == tag.id){
        //tag.hide = false; // Uncomment to update the current array
        freshArr.push(tag);
    }
    // else{ // Uncomment to update the current array
    //      tag.hide = true;
    // }
  })
})

In terms of data manipulation efficiency, Lodash surpasses angular.

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

Tool for tracking response time on basic Ajax-requested webpage

Looking for an easy way to use ajax to load content onto a page. I want the loaded content to wait before appearing on the page, but using jQuery's .delay() function didn't work as expected. Any suggestions on how to achieve this? Appreciate any ...

When moving the React application to the production environment, the message 'Please activate JavaScript in order to launch this application' is displayed

Challenge Encountering an issue with my axios call at "/artists" in production mode. While it functions as expected during development, the response received is undefined, leading to the appearance of an HTML element stating You need to enable J ...

Attempting to transform text into symbols

I'm puzzled by this situation where an infinite loop is created and I can't figure out the reason behind it. Interestingly, the loop doesn't occur when the push command is not used. #words = ["Apple", "Banana", "Cherry", "Date", "Elderberry ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

What is the purpose of creating redirects instead of just "processing" data?

Upon pressing the subscribe button, a form is submitted. Previously, I used axios. The POST request is sent to https://api.skymongoose.com/subscription. Why does it redirect to a blank page even though the URL points to https://api.skymongoose.com/subscri ...

Expressjs encountering issues with response detection

I'm facing an issue with my nodeapp and Express setup. I have configured a reverse proxy through nginx to point to . However, when I start my application, it doesn't seem to recognize the / response. Below is my code snippet: var express = requ ...

Ensuring a URL is W3C compliant and functions properly in an Ajax request

I have a general function that retrieves URLs. This particular function is part of a plugin and returns URLs to various resources such as images and stylesheets within the plugin. GET parameters are used in these URLs for proper functionality. To ensure ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Determine the location of a shape in Kinetic.js while it is moving with the .move() method

I recently started working on an HTML5 game using Kinetic.js, and I'm still getting the hang of it. As a newcomer to HTML5 Canvas development, I've managed to create a simple game where a spaceship moves across the screen based on arrow key input ...

Creating a numpy array in two dimensions using a pair of one-dimensional arrays

Is there a way to transform two numpy arrays, for example: a = [[1, 2, 3]] b = [[100, 200, 300]] into an array structured like this? [[1, 100], [1, 200], [1, 300], [2, 100], [2, 200], [3, 300], [3, 100], [3, 200], [3, 300]] Any suggestions on how t ...

Tips for triggering the onChange event in Formik and initiating a re-render of other components

As someone who is new to React, I am currently working on a webpage with 2 forms. The first form has only one input field while the second form is a component imported from another file. Despite trying to use onChange to update the initial value (initialVa ...

Deciphering the Byte masking concept in Java

As I was optimizing space in a program, I came across some code that intrigued me. private static final long MAX = 1000000000L; private static final long SQRT_MAX = (long) Math.sqrt(MAX) + 1; private static final int MEMORY_SIZE = (int) (MAX >> 4); ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Displaying form after Ajax submission

I have implemented an AJAX code to submit my form, but I am facing an issue where the form disappears after submission. Here is my current code: <script> $('#reg-form').submit(function(e){ e.preventDefault(); // Prevent Default Submissi ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

Guide to integrating the Braintree API with Node.js

I am trying to implement Braintree for website payment gateway, but I encountered an issue while following the online guidelines. The code seems to be incompatible with Node.js. Am I missing something? Index.js: //send token to clients app.get("/client_t ...

Error: The function is invalid for callback at end (node_modules/middy/src/middy.js:152:16)

I seem to be having some trouble with my test when using middy. Removing middy makes the test pass successfully, but with middy, I encounter the error "TypeError: callback is not a function at terminate (C:\cico\node_modules\middy\src&b ...

What is the reason for initializing this Knockout.js component in a seemingly random order?

I am feeling completely lost... Currently, I am working on creating a list using Knockout.js components, templates, and custom elements. However, I am facing an issue where the steps I define in my Viewmodel are being initialized in a random order within ...