Ways to separate two pieces of information within a single element of an array

I am working with an array and trying to split two sets of data that are contained within one element of the array.

Take a look at the code below :

const array = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];

array.map(x => {
  return (
    console.log(x.split(" "))
  )
});

The element array[1] holds two sets of data: 2 Florida 6 14 and 3 Texas 5 12. I need to separate these into different arrays, each containing one set of data from array[1].

This is the expected result :

[
  "1",
  "Boston",
  "4",
  "11"
]
[
  "2",
  "Florida",
  "6",
  "14"
]
[
  "3",
  "Texas",
  "5",
  "12"
]
[
  "4",
  "California",
  "7",
  "13"
]

Can anyone please assist me in finding a solution?

Answer №1

Break down each line first, then separate by spaces

const newArr = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
console.log(newArr.flatMap(element => element.split("\n")).map(elem => elem.split(" ")));

kemicofa noted that not all browsers support Array#flatMap. The suggested alternative for flatMap is a combination of Array#reduce and Array#concat:

const newArr = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];
console.log(newArr.reduce((acc, element) => acc.concat(element.split("\n")), []).map(elem => elem.split(" ")));

Answer №2

Array#flatMap may not work on IE or Edge browsers. An alternative approach involves using Array#join combined with String#split

const data = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"];

const res = data.join("\n").split("\n").map(item=>item.split(" "));

console.log(res);

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

Triggering a button click event in a Jquery UI autocomplete combobox

There seems to be a strange issue happening with the jquery ui autocomplete feature when used to create a combobox. Whenever I scroll through the list of results using the scrollbar and then try to close the results by clicking on the combobox button, the ...

Steps to implementing a function just before a form is submitted

Imagine a scenario where you have the following HTML form: <form action="myurl.com" method="post" id="myForm"> <input type="number" name="number" class="numberInput"> <input type="number" name="number"> <input type="submit ...

Updating ngModel value dynamically from controller

I have been trying to update the value of an ngModel variable from my controller, but it doesn't seem to be reflecting in the views. Despite looking at other solutions on SO, nothing has worked for me so far. I am looking for a solution that doesn&apo ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

Employing angularjs alongside a static jsonp file produces results on the first attempt

Currently, I have data being retrieved from a jsonp file within my application. worm.factory('simpleFactory', function ($http, gf) { var simpleFactory = ""; return { getJson: function ($scope) { var url = 'myfile.json?callback=J ...

Integrating a sleek Bootstrap 5 search bar drop-down functionality

As a newcomer, I could use some assistance with creating a dropdown menu that includes a search bar. Specifically, I want users to be able to select items from a list of foods or search for them. Unfortunately, I haven't been able to find a bootstrap ...

What is the best way to combine PHP and HTML within a JavaScript script?

I'm facing a challenge with integrating dynamically added elements and a populated drop down on my form. Is there a way to combine the two seamlessly? Below is the code snippet I'm using for dynamically adding and removing elements: $(docu ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

Create an HTML file using Jade that is created from user input

My aim is to provide users with the ability to generate a list containing a specific number of entries. For example, if a user inputs "50", a list with 50 entries should be automatically generated. Currently, I am working with Jade and Bootstrap for this ...

I'm struggling to understand the folder arrangement and the system is telling me it can't locate my file

I'm having trouble identifying what might be causing issues with my file structure. Currently, I am using Aurelia for the front end and node for the server. I attempted a fix by performing a join operation, which resolved some of the problems. However ...

`Get the height of a specific element within a FlatList using the index property in React Native`

I'm currently exploring a workaround for the initialScrollIndex issue in FlatList that is not functioning correctly. I attempted to use getItemLayout to address this, but encountered a new problem - my elements inside the FlatList have varying heights ...

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

How can I retrieve a ref from a child component in Vue.js?

As a beginner to vuejs with limited JavaScript experience, I am using Vue3 in Laravel. I have a child component that exposes a ref on an input field like so: <input v-model="raw_input" ref="raw" @input="checkLen ...

"Transforming JSON data into a format compatible with Highcharts in PHP: A step-by-step

Currently facing an issue with converting the given array format into a Highcharts compatible JSON to create a line chart. Although everything else is functioning correctly, I am struggling with this specific conversion task. { name: [ 1000, ...

Transforming a 2D array into an array of objects

Here is an example of an array: let heroes = [ ["1", "Tony Stark"], ["2", "Steve Rogers"], ["3", "Thor"], ["4", "Nick Fury"] ]; I am looking to transform this array into an object with the following structure: let avengers = [ {id:"1", name:"T ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...

What is the best method for converting a modified array back to JSON format?

I'm currently working on a Discord bot that allows users to use the command tcp freeitem to receive a free item. My goal is to update the Account object by adding a new item to the account. However, when I attempt to map the array to replace a value, ...

Following the object's update, the program is incapable of executing the compareTo function

I am currently working on adjusting the product placement within the print menu. After updating some information about the products, I need to sort them by "Quantity" in descending order. In cases where the quantities are the same, the list should be sorte ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...