What is the best way to extract values from an array and then construct a brand new array using

Looking to extract specific data from an array?

var data = new Array("1111_3", "1231_54", "1143_76", "1758_12");

If you want to extract just the numbers before the underscore in data[0] (1111), you can use the following method:

var ids = new Array();
// example: ids = Array("1111", "1231", "1143", "1758");

This code snippet will copy all the extracted numbers into the 'ids' Array. Do you need a PHP-like solution, or is using loops the best approach?

Thank you!

Answer №1

Extremely straightforward:

let ids = [];
for(let k = 0, x = data.length; k < x; ++k) {
   let idString = data[k];
   ids.push(idString.substring(0, idString.indexOf('_')));
}

Answer №2

gracefulness:

data.map(function(item){
    return item.split('_')[0];
})

This element is in accordance with the ECMA-262 standard.

However, if you desire to cater to old, outdated browsers, consider using jQuery (or any other framework you prefer; most of them have a custom map function):

$.map(data, function(item){
    return item.split('_')[0];
})

Answer №3

What you're looking to achieve is known as a 'map' function. Certain browsers have built-in support for this, but for more reliable results, you can consider using underscore.js (http://documentcloud.github.com/underscore/)

You could implement it in one of the following ways:

_(data).map(function(x){
    return x.split('_')[0];
});

or

_.map(data, function(x){
    return x.split('_')[0];
});

Answer №4

When dealing with a large array, it can be more efficient to concatenate it into a string and then split the string rather than using traditional iteration methods.

var data = ["1111_3", "1231_54", "1143_76", "1758_12"];

var ids= data.join(' ').replace(/_\d+/g,'').split(' ');

alert(ids)

/*  returned value: (Array)
1111,1231,1143,1758
*/

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

Tips for accessing specific items within complex arrays from the API at themoviedb.org

Currently, I am in the process of developing a basic Telegram bot that utilizes the API provided by themoviedb.org. $url = 'https://api.themoviedb.org/3/trending/all/day?api_key=' . $weather_token; $films = json_decode(file_get_contents($url), TR ...

Laravel 5.0 facing issues with AJAX requests

For my Laravel 5.0 project, I am utilizing Google API's for Google Oauth login. After successfully retrieving the email and id_token of the currently logged-in user, I aim to send this data to the SigninController to access our own API. The goal is to ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Update or Delete BreezeJS EntityManager After Losing Instance Reference

In the process of developing a CRM application with a single-page application structure, I am integrating BreezeJS and AngularJS. The implementation involves utilizing dynamically-generated tabs to display various modules. Each time a user clicks on a menu ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

ReactJS component state fails to update accurately

Let's say I have a component named Test import {useEffect, useState} from "react"; const Test = (props) => { const [Amount, setAmount] = useState(1); useEffect(()=>{ if(props.defaultAmount){ setAmount(prop ...

Converting HTML table data into a JavaScript array

On my website, I have an HTML table that displays images in a carousel with their respective positions. The table utilizes the jQuery .sortable() function to allow users to rearrange the images by dragging and dropping. When an image is moved to the top of ...

"Mongodb and mongomapper are powerful database tools often used

I am currently working on a Rails app that uses ActiveRecord to manage products. Each product has a category and subcategory, with each subcategory defined by multiple fields within the application. This system has become quite complex and I have been cons ...

Inspect/Adjust button status upon page initiation

In the realm of my custom MVC framework, a favourite button has been introduced. When this button is pressed, it triggers the appearance of a `successfully added to favourites` div. If clicked again, a `successfully removed from favourites` div appears. T ...

Contrasting onevent with addEventListener

After studying various DOM events, I attempted to implement the 'blur' event on the HTML body. My first attempt was with onblur document.body.onblur = () => { dosomething(); } and I also tried using AddEventListener document.body.addEven ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Passing the app variable from Express.js to routes

I am attempting to transfer some data from the app (variable defined as var app = express();) to some Socket.IO related code by sending a value to a middleware in a similar manner: function routes(app) { app.post('/evento', function (req, re ...

Fixed navbar does not collapse when clicking on items on a small-screen device

Currently, I am working with Bootstrap 4 and I was able to resolve a similar issue with Bootstrap 3. However, it seems that Bootstrap 4 is not behaving the same way. I am facing a roadblock and this is the final piece needed to complete the project. This ...

Consecutive pair of JavaScript date picker functions

My issue involves setting up a java script calendar date picker. Here are my input fields and related java scripts: <input type="text" class="text date" maxlength="12" name="customerServiceAccountForm:fromDateInput" id="customerServiceAccountForm:from ...

Transforming the value of a property in a JSON object using JavaScript

I have a JSON object that I am trying to manipulate by changing the value of its property "quantity" "[{"name":"Butter","image":"/static/images/items/dairy/butter.jpg", "price":" 30 uah","quantity":"1","alias":"butter"}, {"name":"Chesse","image":"/stat ...

Responsive React Page Design with Swiper's Breakpoints (Bootstrap Integrated)

I have integrated Swiper React with my React project. It seems that I cannot manipulate the 'slides per view' using Bootstrap directly. If it were possible, I would define the necessary columns and insert the swiper slides within them. Currently ...

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

JavaScript button with an event listener to enable sorting functionality

I am looking to implement a button that will reset all the filters on my page. Any ideas? Currently, I have multiple radio buttons for filtering items based on price, size, and color. My goal is to create a reset button that will remove all filters and r ...

Display a JavaScript variable as an attribute within an HTML tag

let disableFlag = ''; if(value.action.length === 0) { disableFlag = 'disabled="disabled"'; } row += '<td><input type="checkbox" name="create" value="1" class="checkbox" data-action="'+ value.action + '" data-co ...

Accessing environment variables of a running process in Node.js

I am currently developing a vscode extension and I am looking for a way to access the environment variables of a running process. So far, my search has been unsuccessful. In python, I know how to achieve this using psutil: for proc in psutil.process_iter ...