Utilizing the .reduce method on an object with an array of values in order to transform it into an

I am attempting to transform an object with arrays as properties into a single array containing all elements from these nested arrays.

My approach is as follows:

data1 = [{
  a: 1,
  b: ["uz", "vy"]
}, {
  a: 2,
  b: ["wxa", "xwy"]
}, {
  a: 6,
  b: ["ysa", "zaa"]
}]

data1.reduce(function(q, w) {
  return q.b.concat(w.b)
})

The desired output should be:

data1 = ["uz","vy","wxa","xwy","ysa","zaa"]

However, I encounter the following error message:

"Uncaught TypeError: Cannot read property 'concat' of undefined"

If q.b references an array within an object, why does it not have the property concat? Where did I make a mistake in this code?

Answer №1

You received an error because the variable q is an array and does not have a property b. Additionally, you forgot to include the initial value.

To resolve this issue, you can use concat and map.

let data1 = [{a: 1,b: ["uz", "vy"]}, {a: 2,b: ["wxa", "xwy"]}, {a: 6,b: ["ysa", "zaa"]}];

let result = [].concat(...data1.map(o => o.b));

console.log(result);


If you prefer to utilize reduce, follow these steps:

let data1 = [{a: 1,b: ["uz", "vy"]}, {a: 2,b: ["wxa", "xwy"]}, {a: 6,b: ["ysa", "zaa"]}];

let result = data1.reduce(function(q, w) {
  return q.concat(w.b);
}, []); //<-- Include [] as the initial value

console.log(result);

Answer №2

To properly use the reduce function, make sure to provide an initial value. Additionally, in the first call, ensure that you concatenate to q instead of trying to access q.b:

data2 = [{
  a: 5,
  b: ["xyz", "abc"]
}, {
  a: 3,
  b: ["lmn", "def"]
}, {
  a: 8,
  b: ["pqr", "ghi"]
}]

var output = data2.reduce(function(q, w) {
  return q.concat(w.b);
}, [])

console.log(output);

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

When attempting to open a .pdf file in a new tab using React and Express, a void message appears on the screen

I have a situation where I am attempting to open a .pdf file in a new tab from the server's file system using Express, React, and MySQL. The problem arises when, upon clicking the "See" button, the displayCV function is triggered, a new tab opens, but ...

Error: JavaScript function call did not provide a return value

Currently, I am in the process of creating a straightforward angular2/expressJS application. Within my expressJS code, I have an HTTP GET router call that retrieves all users from MongoDB and successfully returns them: app.get('/getusers', funct ...

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

The error message "consts is not defined in React Carousel renderArrow" indicates

While working with the react-elastic-carousel package, I encountered an issue when attempting to implement my own custom arrows. This is the code snippet I used, which was borrowed from the documentation: function App() { return ( <div> ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

What is the functionality of the "respond_with_navigational" feature?

Currently, I am integrating Devise and DeviseInvitable to handle authentication in my application. However, I'm facing challenges when trying to incorporate AJAX functionality into InvitationsController#update. The structure of the controller in Devis ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

What is the best way to access the width of the top-level parent div and adjust the widths of its child and parent divs according

I'm currently working on creating a custom directive in Angular 4 to enable resizing of a div. Here's the HTML code snippet: <div class="super-parent"> <div class="parent"> My Div content <div class="child" re ...

Iterating through a JSON object that contains an array nested within another array using PHP foreach loop

Below is a snippet from a json file: { "status": { "http_code": 200 }, "contents": [ { "FabrikatNavn": "Jaguar", "ModelNavn": "420G", "PrisDetailDkk": 119900, "StatusTyper": [ { "StatusId": -5, ...

Error message: "Error occurred due to the undefined object in React UseEffect and

In my ClientData.js file, I am utilizing the useEffect hook to initiate an API call, which is functioning as intended. Subsequently, I am using useState to assign the response data from the API to a variable, which is also working properly. The retrieved ...

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

Transform a Mobx observable map into a JavaScript array

I am working with a component that receives the value of "form.$('userProfile').fields" as a prop, which is an observable map. The structure of this map can be seen in the console.log screenshot below: class Location extends React.Component<* ...

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

Modify a number with a check box using inline Ajax

I have an HTML structure similar to this example: <li><label class="desc"><font color="green">Want to receive emails ($<span id="price">50</span>/month)</font></label> <input type="checkbox" checked ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

An item possessing a characteristic that can vary in type within the same attribute

I am currently brainstorming the most effective approach for a C++ program: My objective is to create an object named Characteristic with 4 attributes: - String name (simply the name) - ? type (indicating whether it's numeric or descript ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Sliding divider across two div containers with full width

Seeking a JavaScript/jQuery function for a full page slider functionality. The HTML structure I'm working with is as follows: My objectives are twofold: Both slide1 and slide2 should occupy the full width of the page. Additionally, I am looking for ...

Bringing node.js variables into a database

I need help with the code I have written. It seems to be working but instead of updating the database with the actual result from a Node.js variable, it is inputting the string "$var". Can someone assist me with this issue? Thank you. var TOTP = require( ...