The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together.

Please refrain from suggesting the use of bootstrap pagination for angularjs as I have built my own solution that meets my requirements.

$scope.results = [
      {
        "devID": "1",
        "devName": "item 1",
        "desc": "sample desc"
      },
      {
        "devID": "2",
        "devName": "item 2",
        "desc": "sample desc"
      },
      {
        "devID": "3",
        "devName": "item 3",
        "desc": "sample desc"
      },
      {
        "devID": "4",
        "devName": "item 4",
        "desc": "sample desc"
      },
      {
        "devID": "5",
        "devName": "item 5",
        "desc": "sample desc"
      },
      {
        "devID": "6",
        "devName": "item 6",
        "desc": "sample desc"
      },
      {
        "devID": "7",
        "devName": "item 7",
        "desc": "sample desc"
      },
      {
        "devID": "8",
        "devName": "item 8",
        "desc": "sample desc"
      }
    ];

In addition, there is an empty object named $scope.deleteList = {} which gets populated with IDs by the selectAll() function.

Here is the code for my $scope.selectAll() along with some console logs for debugging:

    $scope.selectAll = function(){

        $scope.resultsToDelete = $scope.results.slice(($scope.currentPage * $scope.pageSize), $scope.pageSize);
        console.log("$scope.results:", $scope.results);
        console.log("$scope.currentPage:", $scope.currentPage);
        console.log("$scope.pageSize:", $scope.pageSize);
        console.log("$scope.currentPage * $scope.pageSize:", ($scope.currentPage * $scope.pageSize));

        for (var i = 0; i < $scope.resultsToDelete.length; i++) {
            var item = $scope.resultsToDelete[i]; 
            $scope.devDelList[item.devID] = true;
        }

    };

The expression

($scope.currentPage * $scope.pageSize)
gives me the index of the first object on the next page in the list.

Below is the implementation of my pagination logic:

    $scope.pagination = function(itemList) {
        $scope.currentPage = 0;
        $scope.pageSize = 4;
        $scope.numOfPages = Math.ceil(itemList.length / $scope.pageSize);
        $scope.pageNumbersArray = [];

        for (var i = 0; i <= $scope.numOfPages - 1 ; i++) {
            $scope.pageNumbersArray.push(i);
        }
    }($scope.results)

$scope.prev = function() {
    if ($scope.currentPage > 0) {
        $scope.currentPage = -- $scope.currentPage;
    }
}

$scope.next = function() {
    if ($scope.currentPage < $scope.numOfPages - 1 ) {
        $scope.currentPage = ++ $scope.currentPage;
    }
}

$scope.goToPage = function(pageNum) {
    $scope.currentPage = pageNum;
}

My problem lies in the usage of the .slice() method on the results array. It works correctly only for the first page when $scope.currentPage = 0. However, once $scope.currentPage = 1, the $scope.results.slice() call returns an empty array.

$scope.results.slice(0, 4) provides the correct IDs for the first page containing 4 items.

$scope.results.slice(4, 4) returns an empty array (i.e., []), failing to retrieve the second set of 4 items.

What could be causing this issue?

Answer №1

The function $scope.results.slice(4, 4) will result in an empty array being returned. This means that no elements are included in the extraction (e.g. [])

According to the documentation

The slice() method extracts a section of an array and returns a new array.

It requires two parameters: start index and end index. The extracted portion includes elements starting from the start index up to, but not including, the end index.

For example, calling slice(1,4) will extract elements at index positions 1, 2, and 3.

Therefore, when using slice(4, 4), the result should be an array with zero elements.

You can implement this with the following code:

var startIndex = $scope.currentPage * $scope.pageSize;
var endIndex = ($scope.currentPage * $scope.pageSize) + $scope.pageSize;
$scope.resultsToDelete = $scope.results.slice(startIndex, endIndex);

Answer №2

For more information, check out the slice documentation.

Remember that the second argument in slice is not the length, but rather the end index.

Consider the following array:

arr = [1, 2, 3, 4]

If you want to select elements [3, 4]

You should use slice(2, 4) and not slice(2, 2)

Make sure your code looks something like this:

result = $scope.items.slice(($scope.currentIndex * $scope.limit),
    $scope.currentIndex * $scope.limit + $scope.limit);

Answer №3

anArray.slice(n, n) will always result in an empty array being returned. When using the slice method, it's important to remember that the arguments are (begin, end), where begin represents the start index and end represents the end index, not the length of the slice.

For your specific scenario, you can achieve the desired outcome with the following code:

var start = $scope.currentPage * $scope.pageSize;
var end = start + $scope.pageSize;

$scope.resultsToDelete = $scope.results.slice( start, end );

Answer №4

One reason behind this behavior is that The Slice method operates on a zero-based index Refer to the documentation for more information

Basically, the slice() method creates a new array by copying a section of an existing array from a specified starting point to an ending point (but not including the end index).

Therefore, in the syntax array.slice(begin,end);

The value of 'begin' represents the zero-based index where extraction begins.

The value of 'end' signifies the zero-based index before which extraction ends; slice includes all values up to but not including 'end'.

For example,

var arr = [1,2,3,4];

When we use arr.slice(1,3);, it implies selecting elements from index 1 up to index 4 (excluding the value at index 4), resulting in [2,3].

Consequently, if we execute arr.slice(1,1);, we are essentially specifying indices 1 to 1 inclusive, excluding the value at index 1 and yielding an output of an empty array: []

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

Utilizing ngRepeat to build intricate rows within a table

I have a unique collection that appears as follows: { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, } }, "14": { "10 ...

C Array Losing its Value

Hey everyone, I'm a newcomer to this community and also new to C Programming. I have been using several print statements to check the value at different stages of my code. The issue seems to be related to user input I've noticed that the det[0] ...

Scale the cylinder in Three.js from a specific point

Can a cylinder be resized along the Y-axis starting from a particular point? Instead of the cylinder expanding from its center in both directions to the new scale, is it possible for it to grow upwards/downwards only like a bar chart? Current code : fu ...

Traverse a computed attribute in Vue.js

I am working with a component that contains a simple array as its data: data() { return { roles: [ { id: '1' , name: 'admin'}, { id: '2' , name: 'user'}, { id: &a ...

Getting the http response content of a Slim PHP API with Angular JS: A step-by-step guide

My Slim PHP programmed API sends JSON responses in the following format: $response['some-text'] = 'blabla'; $app->response->setStatus(200); $app->response()->headers->set('Content-Type', 'application/json& ...

Navigating through PWAs and implementing deep linking in both single page applications (SPAs) and multi-page applications

QUESTION: How can navigation, history, and deep-linking be managed in a PWA without relying on a heavy JS Framework? Tasked with transitioning an existing shopping website from Angular 1 SPA to a Multi Page App (MPA) PWA, I find myself grappling with desi ...

Next.js Server Error: ReferenceError - 'window' is undefined in the application

I am currently in the process of integrating CleverTap into my Next.js application. I have followed the guidelines provided in the documentation Web SDK Quick Start Guide, however, I encountered the following issue: Server Error ReferenceError: window is ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Issue with JavaScript not generating a header element within a specified div

function searchingFunction() { var searchInput = document.getElementById("searchbar"); if (searchInput.value != null) { var resultElement = document.createElement("h2"); resultElement.innerHTML = "Search results for " + searchInput.value; d ...

Retrieving the rootScope variable in AngularJS after it has been assigned

Within the project I am currently developing, there exists a variable known as events in the $rootScope. This variable can be accessed in my controllers by utilizing $rootScope.events after properly injecting it into the controller. There is a delay in se ...

Checking form data validity before submission in JavaScript and PHP

My goal is to send data to a PHP script using the POST method. I need to ensure that the form input is valid before initiating an AJAX request. $('#submitccform').click(function() { function validate() { var valid = true; var messa ...

Multiple loop in Node.js with Selenium

I just completed a node script using selenium webdriver for automated testing purposes. Below is the code snippet: var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('unders ...

When calling canvas.getContext('2D'), the function returns a null value

After creating a canvas and calling its getContext() method, I was confused when it returned null for the context. Below is the code snippet that I used: <script> window.onload = initializeCanvas; function initializeCanvas(){ ...

Comparing SailsJS and BreezeJS for Single Page Applications with backend authentication

As I venture into the realm of full stack JavaScript application development, I find myself diving deep into various posts and documentation. However, one particular issue is giving me pause: Two frameworks, SailsJS and BreezeJS (+AngularJS), appear to of ...

This JavaScript function is designed to strip HTML elements from a given

"p" tags are disappearing after running the javascript, but they are needed for structuring purposes. Is there a way to retain the html tags in the hidden/secondary text block even after the javascript manipulation? function AddReadMore() { //This lim ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

Creative ways to use images as borders with CSS in React JS

import React, { Component } from 'react'; class BigText extends Component { constructor(props) { super(props); this.state = { title: '', text: '', summary: '' ...