Manipulate JavaScript arrays: When provided with an array of size n, extract elements from index

I am seeking the most efficient method to solve this problem by utilizing JavaScript's native array methods (map, reduce, etc.).

If given an array of n objects, my goal is to create another array that contains m objects for each element in the original array. Although I can achieve this using traditional "for" loops to iterate through the array, I am curious if there is a solution using the native array methods.

For example:

Suppose I have an array with n elements like "ObjectA":

var objectA = {
       name: "xxx",
       tels: ["yyy","zzz"]
};

I aim to generate another array of objects of type "ObjectB":

var objectB = {
       name: "xxx",
       tel: "yyy"
};

Thus, if the initial array only contained objectA, the desired outcome would be:

[
   {
      name: "xxx",
      tel: "yyy"
   },
   {
      name: "xxx",
      tel: "zzz"
   }
]

I attempted using two nested "map" calls, but encountered limitations as the callback function can only return one element at a time.

var array1 = [objectA];

var array2 = array1.map(function(objectA){
   return objectA.tels.map(function(tel){
      return {
                 name : objectA.name,
                 tel : tel
              };
   });
});

Returning another array within the callback resulted in an array of arrays, which is not the intended outcome. The result of Array2 was:

[
   [
      {
         name: "xxx",
         tel: "yyy"
      },
      {
         name: "xxx",
         tel: "zzz"
      }
   ]
]

Should I resort to using traditional for loops, or is there a native JavaScript approach available?

Answer №1

Using Array.prototype.map on the 'array1' variable will not produce the desired outcome, as it returns an array of the same length.

To achieve a different array length, consider using Array.prototype.reduce first, followed by Array.prototype.map for individual objects in the 'tels' field.

var array2 = array1.reduce(function (prev, curr) {
    return prev.concat(curr.tels.map(function (tel) {
        return {name: curr.name, tel: tel};
    }));
}, []);

Answer №2

Your attempt at using a nested map was on the right track, but it resulted in arrays within arrays. To prevent this, try using forEach and push the results to an array within the inner loop instead:

var result = [];

initialArray.forEach(function(item){
   item.numbers.forEach(function(number){
      result.push({
          name : item.name,
          number : number
      });
   });
});

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

Is there a way for me to display a gif similar to 9GAG on my

I'm looking to implement a feature on my website that allows me to pause and play a gif, similar to the functionality on 9gag. Can anyone provide guidance on how I can achieve this? I understand that I need to use both .jpg and .gif files, but my at ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...

Using Browserify to import a file located in the same directory from an npm repository

I am facing an issue with requiring a specific module in my .js file. This particular module consists of two sibling files, a.js and b.js, with a.js being the main file according to package.json. Both a.js and b.js can be accessed using module.exports. Ho ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

Replicate the contents of one DIV element into a different DIV

I am in need of assistance with cloning a DIV in order to prevent data duplication. This is something I frequently need to do across several pages and I don't want to make major structural changes. My goal is to clone the mApageLeft DIV with the clas ...

Unable to redirect from login page to dashboard using AJAX with Flask backend

Using the post method for login, my ajax function successfully sends data to my flask backend server [confirmed by the response received]. However, after receiving the response from the backend, the ajax success handler fails to navigate/redirect to the da ...

What is the best way to organize data using Data.Vector.Generic.Mutable?

What is the best way to efficiently sort a vast array of data (consisting of strings, floats, etc) that has been imported from a massive file containing millions of lines using a Data.Vector.Generic.Mutable object and a sorting algorithm from Data.Vector ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

An overabundance of parallax visuals

I'm currently working on a static website that features several parallax images dividing each section. However, I've run into an issue as I continue to add more sections and parallax images. Some of the images at the bottom of the website are shi ...

Tips for creating a Selenium Java logic that dynamically switches between two paths depending on the type of question

Currently, I am developing a logic in selenium-java to automate the process of taking tests. During this testing phase, each test-taker may receive either set-1 or set-2 at random for each node. The number of questions in each set may vary Answer data wil ...

An aspect of Javascript that includes a conditional parameter is the Singleton class

I am dealing with two classes: useService.ts import { useMemo } from 'react'; /** * This hook will take the singleton service instance and keep it memoized * @param service */ export function useService<T> ( service: { new (): T; getIn ...

Is it possible to uncheck a checkbox from a list, even if some of them are already unchecked?

I am attempting to implement a feature where checking a checkbox selects all others in the list, and unchecking one deselects all. Currently, only selecting one checkbox allows me to check all the rest, but unchecking one doesn't trigger the reverse a ...

Populating an NSComboBox with information sourced from an array in a separate class

Since my last inquiry about accessing an array from a different class, I have been struggling with a new problem for three days now. No matter how many solution approaches I try, none seem to work. My experience in Cocoa Programming is limited, so I am ho ...

Page experiencing issues with JavaScript functionality

Here is a simple function that I am using to shake a form when the user's email is not valid: function shakeForm() { var l = 10; for( var i = 0; i < 10; i++ ) $("form").animate( { 'margin-left': "+=" + ( l = -l ) + 'px ...

Transform HTML components into visual representations (on the server)

I am looking for a way to convert dynamic HTML elements into image files such as jpg or png. I do not want to capture a screenshot of a webpage or a static HTML file. My goal is to achieve something similar to the following, but executed on the server-sid ...

The error "Unable to load Stylesheet" occurred in a Node.js/Express Application

I've been attempting to include a stylesheet in my webpage using Express, but for some unknown reason, it is not working as expected. When I directly visit the CSS file in the browser, everything appears to be fine, so it seems like there might be an ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

No tests were located for execution. Despite our efforts, a cypress.json file was not found in the search

Having recently set up Cypress in my project, I encountered an issue while attempting to run it using npx cypress run. The error message displayed was: Could not find any tests to run. We searched for a cypress.json file in this directory but did not ...

HowlerJS: Unauthorized Access - Error Code 401

Working with Angular 7, I have developed an application that consumes data from an API. I have successfully implemented CRUD functionalities using an http-interceptor that adds a token to each request. However, I encountered a 401 error when integrating Ho ...

Flashing background color appears as I scroll

Whenever a user touchstarts on a div, I want to apply a background-color to that specific div. Then, as the user scrolls, I use the $(window).scroll event to either reset or remove the background-color from all divs. However, my issue arises when a user b ...