How can you effectively modify the size of elements within an irregular array using JavaScript?

Seeking a more efficient method to adjust the length of an array and its elements. Consider the following initial array:

var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]

The desired output should be:

var arr = [["Name", "Age"], ["Luke Skywalker", "22"], ["Yoda", "900"]]

I have implemented some code but would like to ensure optimal efficiency in adjusting the size of nested arrays. Here is what I currently have:

var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
arr.length = 3; // Removes the Obi Wan entry
console.log(arr);
for(var i = 0; i < arr.length; i++){
        arr[i].length = 2 // Removes lightsaber color
};
console.log(arr)

I am particularly interested in optimizing the for loop as I anticipate working with larger datasets. Appreciate your insights!

Answer №1

The area of code I'm looking to enhance is the for loop.

As it stands, your current approach is already optimized in terms of runtime efficiency. Using alternative methods like slice or map would actually slow things down.


It's important to note that the optimization of this specific for loop may not have a significant impact. Unless you've specifically identified this loop as a bottleneck for performance, there's no need to worry about it. If you have indeed pinpointed this loop as a hindrance, then the array(s) must be incredibly large. :-) Even with arrays totaling 100,000 entries, the processing time should still be minimal.

Let's put it to the test:

const now = performance.now ? performance.now.bind(performance) : Date.now.bind(Date);

// Generating an array with 110k entries, each containing five elements.
const arr = Array.from({length:110000}, () => ["a", "b", "c", "d", "e"]);

// Start the timer
const start = performance.now();

// Reducing the array size to 100k entries
arr.length = 100000;

// Trimming each entry down to two elements
for (const entry of arr) {
    entry.length = 2;
}

// Stop the timer
const elapsed = now() - start;
console.log("Elapsed: " + elapsed + "ms");

I'm seeing around 20ms on my system using Brave, which utilizes V8 as its JavaScript engine (similar to Chrome).

This isn't a comprehensive benchmark, but it does provide us with some insight...

Answer №2

There's a simple trick that can sometimes boost performance - utilizing Array.prototype.splice rather than adjusting the length of an array to delete elements:

var myArray = [["Fruit", "Color"], ["Apple", "Red"], ["Banana", "Yellow"], ["Grape", "Purple"]]

myArray.splice(3); // Eliminates Grape entry
console.log(myArray);
for(var j = 0; j < myArray.length; j++){
    myArray[j].splice(1) // Removes color information
}
console.log(myArray);

To compare the efficiency of both methods, check out this benchmark: .

Answer №3

If you want to split an array into chunks, you can try using the array.splice method:

arr[i] = arr[i].splice(0, 2);

Give this a shot:

var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
arr.length = 3; // This removes the Obi Wan entry
console.log(arr);
for(var i = 0; i < arr.length; i++){
        arr[i] = arr[i].splice(0, 2);
};
console.log(arr)

Answer №4

Here's a handy trick for you to try out:

arr.forEach(function(item) { item.splice(-1) });

The splice(-1) function will actually alter the original array by removing the last element from it.

Answer №5

To efficiently extract specific elements from an array, you can utilize a combination of Array.map and Array.slice:

let arr = [["Fruit", "Color", "Quantity"], ["Apple", "Red", 5], ["Banana", "Yellow", 7], ["Orange", "Orange", 3]];

let result = arr.map(item => item.slice(0, 2));

console.log(result);

Answer №6

Presented here is a straightforward and easily understandable solution for your needs.

let data = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
    for(let i=0; i< data.length;i++){
      data[i].splice(-1, 1)
    }
    console.log(data);

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

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

An assortment of elements with conditional statements

Can anyone help me with a function that returns the price of an item from a list? What happens if the item is not in the list? If it isn't, I want to display "No item found with that name" Any suggestions on how to achieve this? let items = [ ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

Transform a JavaScript object array into a collection of individual values

Given a list of objects structured like this, I am looking to transform it into a list of values based on their corresponding IDs. Original = [ {id: 1, value: 12.2494, time: "00:00:00.14"}, {id: 1, value: 4.5141, time: "00:00:01.138"}, {id: 1, ...

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

The functionality of OBJLoader has ceased to function properly following the implementation of revision

Recently, I encountered an issue while working with the objloader feature of the three.js library to display a cube in a web browser. Everything was working perfectly until I updated to revision 55 from git. Since then, I have been unable to render the c ...

Designing the style of a React datepicker

Currently on my webpage, there is a React datepicker component (https://reactdatepicker.com/). Ideally, when I click on the date, I would like the popper to function as an element within the page rather than a separate window. This is how I envision it: ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

What is the method for determining the number of properties that share a common value?

After fetching a JSON object from an API, I am currently going through the result set and constructing a ticket object. Here is the link to the JSON data: data.ticket.seating.forEach((seat: any) => { this.listings.push({ section: seat ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

Using the "this" keyword is required for an Angular Service-created function

Although this question leans more towards JavaScript than Angular, I encountered an issue while creating a service. The function call looked like this: // controller injects activityApi , then service function call is made var activities = activityApi.get ...

Automatically submitting a form in the absence of the user from the page

Is it possible to automatically submit a form when the user exits the page? Here's the code snippet: <form class="carform" method="get"> <input type="hidden" name="number_plate" value="{{ car.number_plate }}"> </form> I want the ...

Utilizing NGRX to inject reducer state into components

In my current setup, I have a tasks reducer that holds the following structure: { error: false,     loading: false,     tasks: [] } Now, this object is being passed down to a simple component like this: <task-list tasks="tasks$ | async"> ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...

Why is it that when upgrading from version 1.1.0 to 1.4.1, BabelPluginRelay is expecting the plugin context to include "types", but receiving [object Object] instead?

I used to have a fully functional relay modern application with babel-plugin-relay 1.1.0, react-relay, react-compiler, graphql 0.10.x, and react 15.5.x. However, after upgrading them all to version 1.4.1 for babel-plugin-relay, 0.11.7 for graphql, and 16.0 ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

Is it necessary to dispose of node.js domains? When is the appropriate time to do so?

In my Express application, I utilize domains for each incoming request. To ensure that all subsequent middlewares are executed within a domain, I've implemented a middleware. app.use(function(req, res, next) { var d = domain.create(); d.req ...

Limit the ng-repeat results based on search input using a transformation filter

I am currently working with an array of records that are being displayed in an HTML table with filters in the header. However, I have encountered an issue where some values are transformed by filters, causing the ng-repeat filter to fail. <table class= ...

Limit the scope of addClass() to immediate children and not descendants

Looking at the code below: <div class="menu"> <a href="#" class="dropdown-item">Link 1</a> <a href="#" class="dropdown-item">Link 2</a> <ul class="hamburgerMenu__menu--levelTwo"> <li><a href="#" ...

Tips for preventing flex items from having equal height when collapsing

When I try to place elements from an array in a list with display flex, the height of other elements gets modified when one is collapsed. I have attempted different display and inline placement on li elements but nothing has worked so far. Is there a way ...