Data loss in the array

I have a task where I need to slice 3 elements from an array and store them in another array

array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];
rows = 3;

Here is the method I am using

getVertWallStruct = (array, rows) => {
    let i = 1,
        storageArr = [],
        data = [];

    for (let k = 0; k < rows*2; k++) { // everything's ok here
      storageArr.push(array.slice(k*rows, (k+1)*rows));
    }

    data = storageArr;

    console.log("storageArr - ", storageArr, " , array - ", array, " , data - ", data);

    return data;
  }

In this scenario, storageArr is ending up with empty arrays (no data inside). But if I remove the line with data = storageArr; the result is:

storageArr =  [ //this is how storageArr should look like in the end
  [1, 1, 1],
  [0, 1, 1],
  [1, 1, 1],
  [1, 1, 1],
  [0, 1, 1],
  [1, 1, 1]
]

Why are the values getting lost?

Update: Even after copying and pasting code from one of the answers, the method is still returning empty data. Why is this happening?

The code snippet looks like:

getVertWallStruct = (array, rows) => {
    console.log(array, rows); //looks fine here
   
    let iterator = array.values()
    let out = []
    for (let i = 0;i < ~~(array.length / rows); i++){
      out.push([iterator.next().value, iterator.next().value, iterator.next().value])
    }
    console.log(out); //why is this empty ???
    
    return out;
  }

https://i.sstatic.net/WAH8O.png

Answer №1

One approach to achieve this utilizing an Array iterator:

The values() function gives back a new Array Iterator object that includes the values for each index in the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

const array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / 3);i++){
  out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
console.log(out)


An updated version, which appears to be functioning correctly:

Update: Even after copying and pasting code from another answer, the method is returning empty data. Why is that?

getVertWallStruct = (array, rows) => {
    let iterator = array.values()
    let out = []
    for (let i = 0;i < ~~(array.length / rows); i++){
      out.push([iterator.next().value, iterator.next().value, iterator.next().value])
    }
    return out;
  };

console.log(
  getVertWallStruct([1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], 3)
)

Answer №2

To organize the given array into rows, utilize the reduce method. Insert an empty array into the accumulator whenever the index is divisible by the specified number of rows. Then, add the current element to the last array in the accumulator.

const array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];

const rowify = (array, rows) => array.reduce((results, current, index) => {
  if (index % rows === 0) {
    results.push([]);
  }
  results[results.length - 1].push(current);
  return results;
}, []);

console.log(rowify(array, 3));

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

JQuery enables nested sorting functionality

I need to enable the sortable feature specifically for the charts. Index.cshmtml <div id="sortable" class="col-lg-9"> <div class="col-lg-12 col-md-12 padding hidden" id=@($"chartNumber{Model.Charts[ ...

Updating data conditionally and pushing new information in MongoDB database

I am working with a unique MongoDB database structure: { username: "johndoe", shoppingList: { element1: [ { price: 25, time: '2024-02-20T20:00:00.000+00:00' }, { price: 30, time: '2024-02-21T ...

Tips for creating a smooth transition effect using CSS/JavaScript pop-ups?

Looking for some assistance in creating a CSS pop-up with a touch of JavaScript magic. I've managed to trigger the pop-up box by clicking a link, and while it's visible, the background fades to grey. But I'm struggling to make the pop-up fad ...

Content in static JSON file failing to display in NextJS

I recently started using Next, and I've encountered an issue. There is a static JSON file located in the root of my project directory, structured as follows: {"data":[{"id":1,"attributes":{"name":"Test Prod ...

Mastering Tooltip Placement Using CSS or JavaScript

I have been working on creating a CSS-only tooltip for a web application and so far I have managed to create some useful tooltips with different classes: tooltip-up tooltip-down tooltip-left tooltip-right The distinguishing factors between them are t ...

Using an array as a parameter in a function call

Looking to transfer an empty array from the main function to a user-defined function in Python. Within the function, user inputs will be added to the array and then returned to the main function upon calling. The inputs will be in string format. As a newc ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

The performance of Three.js significantly decreases when utilizing onMouseMove in conjunction with RayCaster

I am currently working on an application using three.js, but I am encountering serious performance issues. This particular part of the application is inspired by the Voxel Painter example. In my version, the user initiates placement by clicking on a cell, ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Having trouble getting the vue-slick-carousel to function properly when using it from the CDN

Struggling to implement a small app using the CDN script at , but so far no success. I'm a novice with vue.js and unsure if I need to import anything. According to the documentation, importing is required: Vue-slick-carousel Following this structure ...

Finding matches within a specific group in regular expressions

I am currently tackling the challenge of implementing a feature that involves detecting and linking phrases like "Co. Reg. No" in a specific HTML element. <div class="entry">The company with Co. Reg. No 1241515 will...</div> My goal is to cre ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...

Here's a helpful guide on verifying the presence of a value within an array in Quasar

const myproducts = ref([]) const items = ref([ { id: 1, item: 'Vaporub 50Gm' , barcode: '123456'}, { id: 2, item: 'Herbal Cool Oil (300+100)Ml', barcode: '123456' }, { id: 3, item: 'live Oil Bp 70M ...

JavaScript Cookie to Ensure Form Submission is Limited to a Single Instance

Seeking assistance with automatically submitting a form on page load using JS cookies. Here is the code I have, but it's not functioning as expected. Any guidance would be greatly appreciated. Thank you. I'm unsure about the section in my code th ...

Get the ability to overlay text onto an image by using jQuery for downloading

Currently, I am facing an issue with an online photo editor in my project. The problem is that I am unable to download the image after adding and editing text on it. The texts added are editable but the image cannot be downloaded after the changes. I nee ...

Creating a User Registration and Authentication System with JavaScript for a Database

I'm new to the world of web development and I've encountered a bit of a challenge. I'm looking for a Javascript framework that can handle user registration and authentication with a database, similar to what I would do with PHP and MySql. I ...

Choose between using a function as a parameter or an instruction when making a selection based on change

I am curious about the distinction between the following two sentences: $('#select').on('change', function() { Manager.doRequest(); }).trigger('change'); And these variations: $('#select').on('change&apos ...

I'm having trouble modifying the backdrop to 'true' or removing it after setting it to 'static' in Bootstrap. Can anyone help me troubleshoot this issue?

I have been encountering an issue with changing the backdrop setting from 'static' to 'true' in Bootstrap modal. Here is the code I am using: $('#modal').modal({backdrop: 'static', keyboard: false, show: true}); ...