Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete.

 var arr = "this is a string 5.86 x10‘9/l 1.90 7.00"
   .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g)
   .map(function (v) {return v;});

 console.log(arr);

 arr = [5.86, 10, 9, 1.9, 7]

Desiring an even mix of string type chunks like "x10‘9/l" in the array:

 arr = ["this is a string", 5.86, "x10‘9/l", 1.9, 7]

Any ideas on how to achieve this?

Answer №1

 let resultsArray = [];

 let sentence = "here is an example of different numbers 8.75 x10‘5/l 4.32 11.50";

 resultsArray.push(sentence.split(" ").reduce((accumulator, part) => isNaN(part) ? accumulator + " " + part : ((accumulator && resultsArray.push(accumulator)), resultsArray.push(+part), ""), ""));

Answer №2

Here is my solution:

 let string = "this is a long text with numbers 10.5 x10‘5/l 2.50 9.88";
 let wordsArray = [];
 wordsArray.push(string.split(" ").reduce((accum, part) => isNaN(part) ? accum + " " + part : (wordsArray.push(accum.trim(), +part), ""), ""));

 let finalResult = wordsArray,
     arrayLength = wordsArray.length, index;

 for(index = 0; index < arrayLength; index++ ) {
     finalResult[index] && finalResult.push(finalResult[index]);  // duplicate non-empty values
 }

 finalResult.splice(0 , arrayLength);  // keep only the non-empty values in the array
 console.log(finalResult); 

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

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

The Facebook Comments widget causes the webpage to automatically scroll to the bottom on older versions of Internet Explorer like

My webpage is quite lengthy and includes a Facebook comments widget at the bottom. However, when loading in IE7 and IE8, the page instantly jumps to the bottom due to this widget. Interestingly, removing the widget allows the page to load normally. This ...

Experiencing a problem with Datatables where all columns are being grouped together in a single row

After creating a table with one row using colspan and adding my data to the next row, I encountered an issue with the datatables library. An error message appeared in the console: Uncaught TypeError: Cannot set property '_DT_CellIndex' of unde ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

JSF Ajax call: Invoking a JavaScript function at the completion

Working on a project with JSF 2.0, here is the form being used: <h:form id="fff" onsubmit="reloadMap();"> <h:selectOneMenu value="#{rentCarPoolBean.state}"> <f:selectItems value="#{rentCarPoolBean.stateList}" id="stateList" /> ...

Javascript - The art of accessing an anonymous array

I'm trying to extract data from an API, but I've run into a snag. There's a list without a name attached to it, making it impossible for me to access the values inside. Here's a simplified example of what I mean: (Here is the JSON stru ...

Using React with Typescript: Can the parent component access data fetched from a nested child component?

Can I access data retrieved from a child component (using a graphql query) in a parent component? For example, how can I use the data fetched by React-component-4 in React-component-1? Is there a way to do this or do I have to duplicate the data fetching ...

Tips for personalizing and adjusting the color scheme of a menu in ant design

I am currently working on a website using reactJs and ant design. However, I have encountered an issue with changing the color of a menu item when it is selected or hovered over. Here's the current menu: Menu Image I would like to change the white col ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...

Tips for removing the y-axis line in ChartJs

How can I hide the y axis line in a bubble chart? I attempted to use the code snippet below but it did not work as expected. yAxes: [{ angleLines: { display: false } }] ...

Repeated instances of the same name appearing in the dropdown list every time the tab button is clicked

When using my function in the onclick nav tabs event (triggered by clicking on any tab), I have a requirement where I need to ensure that no duplicate names are inserted into the dropdown list. The current function is working perfectly, but I am looking fo ...

The variable in the dataTables JavaScript is not receiving the latest updates

//update function $('#dataTable tbody').on('click', '.am-text-secondary', function() { //extract id from selected row var rowData = table.row($(this).parents('tr')).data(); var updateId = rowData.id; ...

The functionality of JQuery's `.on("click"... is sporadically functioning

I have a code block that dynamically generates elements and includes event handling. However, the event handling sometimes works and other times it doesn't. I'm not sure how to debug this issue. Can someone help me figure out what might be causin ...

Challenges of Integrating Auth0 with Angular2/.NETCore Project

I am struggling to integrate this Custom Login auth0 service because I am facing issues with the imports. The problem arises specifically with the usage of declare var auth0: any. Every time I attempt to use it, I encounter the following error: EXCEPTION: ...

Using importNode in the context of Microsoft Edge involves transferring a

I am facing an issue with a dynamic page that has the ability to change its main div content using a bar button. The pages are mostly static except for one which contains JavaScript (RGraph charts). To make it work, I am currently using the following code ...

Attempting deletion with Node.js's Mongoose Framework

Having some trouble with the following code snippet. It doesn't seem to be functioning correctly and is resulting in a 404 error. Any insights on how to troubleshoot this issue? app.delete("/tm/v1/tasks", (req,res) => { Task.findOneAndDelete ...

Tips on changing the default value of a Material UI prop method in React JS

Currently, I'm utilizing React JS and I've brought in a component from Material UI known as (https://material-ui.com/api/table-pagination/). My goal is to customize the Default labelDisplayedRows that looks like this: ({ from, to, count }) => ...