Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one:

var array=  [
    [1,"dataA","dataB","dataC","dataD"...],
    [2,"dataA","dataB","dataC","dataD"...],
    [3,"dataA","dataB","dataC","dataD"...],
    [4,"dataA","dataB","dataC","dataD"...]...
    ];

If we slice each array using slice(0,3), the resulting new array would look like this:

var resultSecondArray=[
        [1,"dataA","dataB"],
        [2,"dataA","dataB"],
        [3,"dataA","dataB"],
        [4,"dataA","dataB"]...
]; 

Answer №1

To achieve the desired outcome, you can utilize either a forEach() loop or map(). This involves pushing the sliced original array items into a second array.

var array=  [
    [1,"dataA","dataB","dataC","dataD"],
    [2,"dataA","dataB","dataC","dataD"],
    [3,"dataA","dataB","dataC","dataD"],
    [4,"dataA","dataB","dataC","dataD"]
    ];
    

var resultSecondArray= [];

array.forEach (function(arr){
  resultSecondArray.push(arr.slice(0,3));
})

console.log(resultSecondArray); // yields [[1, "dataA","dataB"],[2, "dataA","dataB"],[ 3, "dataA", "dataB"],[ 4,"dataA", "dataB"]]

You can also use map() for a similar outcome

let array=  [
    [1,"dataA","dataB","dataC","dataD"],
    [2,"dataA","dataB","dataC","dataD"],
    [3,"dataA","dataB","dataC","dataD"],
    [4,"dataA","dataB","dataC","dataD"]
    ];
    

let resultSecondArray= array.map(arr => arr.slice(0,3));

console.log(resultSecondArray); // yields [[1, "dataA","dataB"],[2, "dataA","dataB"],[ 3, "dataA", "dataB"],[ 4,"dataA", "dataB"]]

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

Creating flexible items with a 1:1 ratio and ensuring that the padding on the left and right of the flex container remains consistent

Whenever I adjust the size of the window, https://i.sstatic.net/Fm3d1.png the flex-container ends up with uneven padding on the left and right, which is less than ideal. So, I am looking for a way to allow the flex-item to resize when the window size c ...

The Angular NgFor directive can only be used to bind data to Iterables like Arrays

I am encountering an issue when attempting to iterate through and display data using ngFor. The specific error appearing in the console is "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only su ...

Develop a jQuery dialog box without assigning an ID

I need help with jQuery to create a dialog that opens and then populates with values. When I tried to create the dialog using jQuery, it kept using old values because the div already existed on the page. I want to create a new instance of the dialog usin ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

jQuery: Revealing or concealing several divs upon selection alteration

When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN. Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hi ...

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

Efficiently organize Arrays within the controller when retrieving from the database using PHP

In my controller, I am passing an associative array called $pagedata to the view. This array contains 3 more associative arrays, which are used to render select elements in the view. I need to sort these 3 arrays without repeating the sorting process multi ...

What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format. app/controllers/rando ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

Utilize a newly created MouseListener object in a separate Java class

Hello there, I've been working on creating an animated character for a multitouch screen, and I have a specific idea in mind. I want this character to have five eyes, with each eye having a pupil that can be dragged and dropped independently within t ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

JavaScript Empty Input Field when Duplicating Node

I am seeking advice on how to clear the textboxes when an HTML form is cleared. The following JS code runs onclick: var counter = 0; function moreField() { counter++; var newFields = document.getElementById('readroot').cloneN ...

Increase the jQuery level and utilize the .find() method

Currently, I am delving into the realm of jquery and facing a minor hiccup with selectors. Below is the structure of my DOM: <li> <header class="title"> <span>Text</span> <a href="#work-1">My trigger</a> ...

`methods that exhibit peculiar behaviors`

My routes are set up with the get method. app.get("/info/teachers", controller1); app.get("/info/teachers/:teacherid", controller2); app.get("/info/students", controller3); app.get("/info/students/:studentid", contr ...

Encountering a TypeError when utilizing a npm hashtable within an object definition

I am currently working on setting up a basic stream to read and parse JSON data and then add key-value pairs to a hashtable. My end goal is to create a module that can be utilized in another program, but as I'm troubleshooting, I've hit a roadblo ...

Having trouble obtaining a GuildMember's displayName in Discord.js leads to a TypeError

I'm completely baffled by the situation here. My code is integrated within the Akairo Framework, yet the error seems to be pointing fingers at discord.js itself. Take a look at the error message below: /home/runner/guard/Listeners/automod/nicknames.js ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...