Is there a way to avoid adding this final "faulty state" to the array?

While working on dynamically slicing an array, I noticed that my while loop was causing an extra slice to be added when it broke the conditional. Even though I can achieve the desired functionality by removing the last element with arr.pop(), I am curious as to why this is happening.

slices(num){
    let arr = [this.digits.slice(0, num)]
    let i = 0
    if (this.digits.length < num){
            throw new Error('Slice size is too big.')
    } else {
        while (arr[i].length === num){
            i++
            arr.push(this.digits.slice(i, num + i))
        }
        // arr.pop() - removed for testing
        return arr
    }
}

For example, let's say we want to slice the following array:

this.digits = [ 3, 1, 0, 0, 1 ]

The expected output should be:

[3, 1, 0], [1, 0, 0], [0, 0, 1]]

However, without using arr.pop(), the algorithm unexpectedly adds an extra iteration resulting in a slice with less length than what is required by the conditional (num == 3)

The actual output will look like:

[[3, 1, 0], [1, 0, 0], [0, 0, 1], [0, 1]]

I understand why the last element is being added due to the fulfillment of the conditional by the previous element. How can I elegantly handle this issue without resorting to using .pop()?

Thank you all for your solutions and feedback! While all responses seem effective, Peter B's implementation stood out for its simplicity and effectiveness. Just a few tweaks and it worked perfectly. Thank you once again!

Answer №1

Incorrect condition check is being performed in the while loop. It's recommended to determine the number of sub-arrays that need to be added within the loop (in addition to the initial array), and iterate up to that count. Here's a revised version:

var digits = [3, 1, 0, 0, 1];

function slices(num) {
  let arr = [this.digits.slice(0, num)]
  let i = 0
  if (this.digits.length < num) {
    throw new Error('Slice size is too big.')
  } else {
    var sliceCutoff = this.digits.length - num;
    while (i < sliceCutoff) {
      i++
      arr.push(this.digits.slice(i, num + i))
    }
    return arr
  }
}

console.log(slices(3));

Answer №2

To determine if the remaining items are sufficient to form an array of the desired length, a single loop that continuously checks the current index, desired size, and total length is needed.

It is not necessary to examine the last array after splicing as it creates unnecessary overhead.

function slice(array, n) {
    var result = [], 
        start = 0;
    
    while (start + n <= array.length) {
        result.push(array.slice(start, start++ + n));
    }
    return result;
}

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

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

Answer №3

Description

Here is a modified version of the code that removes redundant elements and enhances readability. I have simplified the code by eliminating the unnecessary `while` loop and `else` clause.

In this demo, I have defined `digits` as a parameter. You can easily customize this to suit your specific application needs without requiring much guidance.

function getSegments(digits, num) {
  const segments = [];

  if (digits.length < num)
    throw new Error('Slice size exceeds array length.')

  for (let i = 0; i != num; i++)
    segments.push(digits.slice(i, num + i));

  return segments;
}

var inputDigits = [3, 1, 0, 0, 1]; // Input data for demonstration purposes.
console.log(getSegments(inputDigits, 3));

Answer №4

Almost there! My proposed solution maintains the essence of your idea. The issue you're encountering is that by checking arr[i].length against num, you are only verifying the length of the last item added to the array, not the upcoming one. To address this, make sure to verify the length before adding a new item.

this.digits = [ 3, 1, 0, 0, 1 ];

function slices(num) {
    let arr = []
    let i = 0
    if (this.digits.length < num) {
            throw new Error('Slice size is too big.')
    } else {
        while (this.digits.slice(i, num + i).length === num){
            arr.push(this.digits.slice(i, num + i))
            i++
        }
        // arr.pop() - removed for testing
        return arr
    }
}

console.log(slices(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

Tips for creating a simulated asynchronous queue with blocking functionality in JavaScript or TypeScript

How about this for a paradox: I'm looking to develop an asynchronous blocking queue in JavaScript/TypeScript (or any other language if Typescript is not feasible). Essentially, I want to create something similar to Java's BlockingQueue, but inste ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Using Angular components to manipulate the CSS in the DOM

Struggling with dom manipulation in an angular/node.js environment using typescript for my visualcomponent.html The second inline styling works fine, showing the h1 in blue color. However, I run into issues when trying to embed strings within the innerHTM ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

Is the HTML5 type of button functioning properly, while the type of submit is not working as

Looking to validate a form before running a JavaScript function? Check out this code snippet: function updateMap() { //dummy } <form> <div class="group"> <input type="number" id="hour" min="0" max="23" required> <span cl ...

AngularJS POST request encounters failure: Preflight response contains improperly formatted HTTP status code 404

I have encountered a persistent issue with microframeworks while attempting to perform a simple POST request. Despite trying multiple frameworks, none of them seem to handle the POST request properly: Here is an example using AngularJS on the client side: ...

What is the best method for deleting an item from an array with irregular dimensions?

labels = np.array([[-100,32,34,25,2,35,2,5,-100,-100],[-100,35,2,5,-100,-100]]) pred = np.array([[8,32,3,25,2,3,2,5,8],[8,3,2,5,8]]) To remove the -100s in the 'labels' array and retrieve the corresponding elements from the 'pred' arra ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

What is the best way to assign a series of radio buttons to an array within an Angular controller's model?

Let's say I have a controller that contains an array property named 'houses'. I want to use ng-repeat to display this array on a table row with a set of radio buttons (true/false, etc.). How can I ensure that selecting any of these radio but ...

I'm receiving a TypeError in Nodejs indicating that the hashPassword function is not recognized as a function. Can anyone offer advice on how to

How's everything going? I could really use your assistance! I'm currently working on developing an API for registering authenticated users, with data storage in the MongoDB Atlas database (cloud). Unfortunately, I've run into a troubling er ...

Adjust hover effects based on true conditions

Currently working on a web app using HTML, CSS, JavaScript, and AngularJS. Progress so far includes a clickable box that triggers a javascript function to display more boxes upon click using ng-click. <div ng-click="!(clickEnabled)||myFunction(app)" cl ...

How can I verify if my discord.js bot has the necessary permissions from a server or channel?

I need to verify two things: Determine if my bot has a particular SERVER permission (return true/false based on the presence of that permission) Confirm if my bot possesses a specific CHANNEL permission (return true/false depending o ...

The system has removed all content within the fields

I have created a code to generate a dynamic table. The problem I am facing is that when there are multiple rows in the table, clicking on the delete button deletes all field values instead of just deleting the data for the specific row where the delete b ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Retrieve information from a variety of selected checkboxes

Is there a way to retrieve the values of check boxes that are generated dynamically? @ $db = mysql_connect("abc", "abc", ""); mysql_select_db("abc"); $strSQL = "SELECT * FROM student"; ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...