Organize and generate a fresh array using AngularJS

I am working with an Array containing objects:

$scope.items1 = [
  [
    {         
      "answer": "BARCELONA",
      "idcustomer": 6,
      "order": 1.1
    },
    {
      "answer": "REAL MADRID",
      "idcustomer": 6,
      "order": 1.4
    },
    {
      "answer": "LYON",
      "idcustomer": 6,
      "order": 1.2
    },
    {
      "answer": "BAYERN",
      "idcustomer": 6,
      "order": 1.3
    }
  ],
  [
    {
      "answer": "BENFICA",
      "idcustomer": 7,
      "order": 1.2
    },
    {
      "answer": "ARSENAL",
      "idcustomer": 7,
      "order": 1.4
    },
    {
      "answer": "CITY",
      "idcustomer": 7,
      "order": 1.1
    },
    {
      "answer": "UNITED",
      "idcustomer": 7,
      "order": 1.3
    }
  ]
];

I have a task to extract specific values from this array and produce a new one.

The desired final result should include: - The first position representing the idcostumer. - Sorting based on the order attribute. - Including only answers with the attribute answer.

$scope.result = [

    [6, "BARCELONA", "LYON", "BAYERN", "REAL MADRID"],
    [7, "CITY", "BENFICA", "UNITED", "ARSENAL"]

];

https://i.sstatic.net/47oVm.png

Any help or advice on achieving this outcome would be greatly appreciated.

Answer №1

It seems like utilizing the reduce method would be beneficial in your situation. reduce enables you to iterate through an array to gather values.

Both structures should function adequately; however, they will impact how you formulate your method to transform the data according to your preferences. Let's focus on the first approach:

$scope.result = $scope.items1.map(function(answerData){
    answerData = answerData.sort(function(a, b) {
        return a.order < b.order ? -1 : 1
    });
    return answerData.reduce(function(result, value) {
        result.push(value.answer);
        return result;
    }, [answerData[0].idcustomer]);
});

Breaking this down, we employ map to iterate over your $scope.items1 array and generate a return for each value within it. Given that $scope.items1 is a 2D array, each answerData will also be an array. Initially, we sort the answerData array by order. Subsequently, we utilize reduce on each of the answerData arrays to produce an array containing only the idcustomer along with each answer field. The callback function for reduce includes two parameters: result and value. For each value, we append its answer field to the result array and then return the updated array.

The process of extracting the idcustomer field from the initial answerData element might seem unconventional, hence the second data structure could potentially offer a more fitting solution. Feel free to explore how to implement that transformation!

UPDATE: After revising your question to include solely the alternative structure, here's the necessary conversion:

$scope.result = $scope.items.map(function(answerData) {
    var sortedDescription = answerData.description.sort(function(a,b) {
        return a.order < b.order ? -1 : 1;
    });
    return sortedDescription.reduce(function(result, value) {
        result.push(value.answer);
        return result;
    }, [answerData.idcustomer]);
});

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

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

Constructor for Mongoose schema not being detected

I am facing an issue in my Node server where I am using Mongoose with a User schema to create a signup function. The error message I am receiving is: TypeError: this is not a constructor This error is coming up in the following code block: var mongoos ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

Designing a framework capable of interpreting Python code and translating it into HTML format

Greetings everyone! I come to you seeking assistance after searching through Google and coming up empty-handed. As a dedicated school teacher, I am in the process of developing an ELearning platform for my students. Right now, my main focus is on creating ...

The application appears to be overloaded with tasks on its main thread, potentially causing errors

I am currently in the process of developing an app for user login and registration. The app relies on receiving a JSON response from a webservice to interact with the database. However, during the registration process, I encountered the following error mes ...

Exploring Firebase database with AngularJS to iterate through an array of objects

I'm working on an app that pulls data from a Firebase database, but I'm running into an issue. When I try to loop through the data and display it on the page, nothing shows up. However, if I use console.log to output the data, it's all there ...

Guide on sending formik initialState to a function as an argument

I'm currently working with Formik in my React application and I'm facing some confusion on how to pass a Formik value prop as a parameter into a function. Assume that the Formik values are as follows: "props": { "myJobName&quo ...

Spacing the numbers on the D3 Y Axis by intervals of 25

Below is the D3 js code I am working with: const svg = select(svgRef.current); const { width, height } = wrapperRef.current.getBoundingClientRect(); const stackGenerator = stack().keys(keys); const layers = stackGenerator(data); const extent = [0, 100]; ...

Retrieving user birth dates via the Facebook API

Having some issues with the Facebook API. I am attempting to request permission for user information using Javascript: FB.login(function (response) { if (response.authResponse) { // authorized } else { // canceled } }, {scope: ...

Utilizing the variable's value as a parameter in a jQuery selector

I am having trouble replacing $('#divy a:lt(3)') with the variable instead of a hard-coded number like $('#divy a:lt(count)'). Check out this Fiddle for more information. var timerId, count = 0; function end_counter() { $('# ...

Angular testing does not recognize the variable

I'm currently testing an Angular app in Protractor and I'm puzzled by a certain issue that keeps occurring. Here's the test code snippet: beforeEach(function() { browser.get('http://localhost:8080/#/'); ... ...

Using AngularJS to inject a service into a static property of a standard class

For my current project, I am combining TypeScript and AngularJS. One of the challenges I'm facing is how to instantiate a static member of a public class (not controller, just a normal class) with a service object. When it comes to controllers, utiliz ...

Omit specific TagNames from the selection

How can I exclude <BR> elements when using the statement below? var children = document.getElementById('id').getElementsByTagName('*'); Is there a special syntax for getElementsByTagName that allows me to achieve this, or is the ...

Using a single quote in JsonConvert.SerializeObject causes the method to fail

Consider this object: public class Comment { public string Id { get; set; } public string Author { get; set; } public string Body { get; set; } } Whenever there is a single quote in the body (the other variables will not contain single quotes ...

Utilizing AJAX within an Ember.RSVP.Promise

I'm curious about the necessity of using the "return" keyword in the common code snippet below when invoking AJAX requests. Specifically, is it necessary for the $.ajax function (considering that $.ajax already returns a promise), or does it serve ano ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

Learn the way to extract an array from the appsettings.json file using .Net 6

I recently came across this amazing Stack Overflow thread about accessing the appsettings.json file in a .Net 6 console application. Interestingly, my own JSON file contains multiple arrays: "logFilePaths": [ "\\\\se ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

Guide to triggering a method upon initialization of a select box in an Angular application

I have a situation where I am using a select box within a dynamically generated row. The row is created using a loop, and I need to execute a method when the select box is initialized. This method should receive the data associated with the row as an argum ...

Troubleshooting error messages in the console during conversion of image URL to Base64 in AngularJS

While attempting to convert an image URL to Base64 using the FromImageUrl method, I encountered an error in my console. Access to the image located at '' from the origin 'http://localhost:8383' has been blocked due to CORS policy ...