Ramda array concatenation problem

Is there a way to concatenate two arrays in Ramda.js?

Here is the data I am working with:

const inputData = {
  content: [
    {

      info: ['Test-1-1', 'test-1-2'],

      moreInfo: ['foo', 'bar'],

      firstName: 'first',

      lastName: 'lst',

      notes: 'Some info goes here'

    },
        {

      info: ['Test-2-1', 'test-2-2'],

      moreInfo: ['foo-2', 'bar-2'],

      firstName: 'first',

      lastName: 'lst',

      notes: 'Some info goes here-2'

    },
  ]
}

I can manipulate this data easily, but I am struggling to merge two arrays together.

What I want to achieve is combining:

info: ['Test-2-1', 'test-2-2'],
moreInfo: ['foo-2', 'bar-2'],

And returning:

"theInfo": ["Test-1-1", "test-1-2", "foo", "bar"]

This is the code I have so far:

const allInfo = (R.props(['info', 'moreInfo']));

const returnNewObject = R.applySpec({

 // More code here to do other stuff

  theInfo: allInfo,

})

R.map(returnNewObject, inputData.content)

The result I am getting is:

{
  // other info

  "theInfo": [["Test-1-1", "test-1-2"], ["foo", "bar"]]
}

I have attempted to use the example from the documentation:

  • use example from documentation

R.concat([4, 5, 6], [1, 2, 3]);

However, it returns an array of empty objects. It seems to not work as expected based on the documentation

Answer №1

Here is the solution:

const combinedInfo = R.compose(R.flatten, (R.props(['info', 'extraInfo'])))

Finally, it yields a flattened array:

["Example-1A", "example-1B", "baz", "qux"]

Answer №2

If you're looking to achieve something similar, you can try the following code snippet (with an additional field combination for demonstration purposes):

const extract = applySpec ({
  theInfo: compose (unnest, props (['info', 'moreInfo'])),
  fullName: compose (join (' '), props (['firstName', 'lastName'])),
  notes: prop ('notes')
})

const process = evolve ({
  content: map (extract)
}) 

const inputData = {content: [{info: ['Test-1-1', 'test-1-2'], moreInfo: ['foo', 'bar'], firstName: 'first', lastName: 'lst', notes: 'Some info goes here'}, {info: ['Test-2-1', 'test-2-2'], moreInfo: ['foo-2', 'bar-2'], firstName: 'first', lastName: 'lst', notes: 'Some info goes here-2'}]}

console .log (process (inputData))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {applySpec, compose, unnest, props, join, prop, evolve, map} = R </script>

If there's no other use for it, you can embed extract inside process as shown below:

const process = evolve ({
  content: map (applySpec ({
    theInfo: compose (unnest, props (['info', 'moreInfo'])),
    fullName: compose (join (' '), props (['firstName', 'lastName'])),
    notes: prop('notes')
  }))
})

The debate arises on the added value of Ramda compared to a vanilla JS version:

const process = ({content, ...rest}) => ({
  ...rest,
  content: content.map (({info, moreInfo, firstName, lastName, notes}) => ({
    theInfo: info .concat (moreInfo),
    fullName: `${firstName} ${lastName}`,
    notes
  }))
})

If Ramda is already in use within your project, opting for the slightly more declarative Ramda version might be favorable. However, adding Ramda solely for this purpose may not be justified.

Answer №3

One option is to utilize the .flat method in order to collapse the array.

theData.flat() //["Test-1-1", "test-1-2", → "foo", → "bar"]

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 to verify if the password entered by the user matches the input provided in the old password field?

I am trying to compare the user's password with the one entered in the "oldPassword" input field. The challenge is hashing the input from the "oldPassword" field for comparison. How can I achieve this? Please review my ejs file and suggest improvement ...

Utilizing Directional and Spotlight Lighting with ThreeJS Helper Functions

I am currently utilizing a guide on implementing light in Threejs from Light in Threejs. I have successfully added some light to my scene. Now, I am attempting to add light to the character in my game but it is still not working. Even though I used the co ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

Extracting timestamped text data from a simulated chat interface

I am looking to gather chat data from Twitch clips. These are saved moments from livestreams where viewer reactions are captured. Take a look at this example clip: While I can scrape all the data by watching the video and utilizing query selectors, my goa ...

Material UI - Radio buttons do not properly reflect the current state of the value

I'm diving into the world of full stack development and I'm working on a project to enhance my understanding of frontend programming with React JS and Material UI. Specifically, I've created a Dialog component to send data to the backend, bu ...

Transforming a set of properties into an organized array

Looking to transform an object literal that contains inner objects with a "rank" key holding floating point values into an array of these inner objects, sorted by the "rank" value. Input Object: { 452:{ bla:123, dff:233, rank:2 }, 234:{ ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

Unlock the power to toggle dynamic elements with jQuery

I'm currently using jQuery to enable and disable input elements, but I'm having trouble doing so for similar elements with the same class. Here is the HTML code: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">< ...

I'm having trouble understanding how to utilize startAt and endAt in Firebase version 9

Trying to implement geo querying in my firestore db with the new version of firebase has been challenging. The code examples provided in the documentation reference an older version, making it difficult for me to understand how to use ".startAt" and ".endA ...

The functionality of JQuery .change() is limited to one occurrence

Here is my JavaScript code snippet: jQuery(document).ready(function(){ const select = $('...'); //select element const input = $('...'); //input element select.change(doSomething()); input.change(doSomething()); f ...

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

What are the benefits of receiving responses in JSON-stringified format on the frontend?

According to findings in this research, JSON parsing is more efficient than JavaScript object literals. With that in mind, could it be considered optimal to receive API responses in JSON-stringified format? It seems logical that parsing a JSON-stringified ...

What is the best way to incorporate next and previous buttons into my slideshow using jQuery?

Looking to enhance my slideshow by incorporating the ability to pause, go to the next or previous image, along with the automatic transitioning feature currently in place. I'm a bit unsure on how to implement these event handlers efficiently within my ...

Issue with Color in Line Chart of Flot Version 0.8.2

While working on Flot line charts and customizing their colors, I came across a strange issue. Once I set the first 3 colors, the plot started using the last color for all the remaining lines. This behavior was unexpected and not the norm. What adds to th ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

What is preventing us from creating a dynamic array in Java?

I have been attempting to create a dynamic array, but I am having trouble getting it to work. After searching for help online, I keep coming across answers that suggest Java arrays are fixed and require extra effort to make them dynamic. However, I can&apo ...

The app.post function is malfunctioning, displaying the error message: "Cannot GET /up."

In the /index.jade file, there is a button that triggers the function window.location.replace("https://upload-andsize.glitch.me/up") when pressed. This function simply redirects from / to /up, which is working fine for GET requests. However, POST requests ...