Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading.

My current setup looks like this:


var n = 100;
var myData = [];
function loadMovies(n){
  // async ajax requests
  // add items to myData using myData.push()
}
loadMovies(n)

var app = new Vue({
  router,
  data: {
     option_n_movies: n
    ,movies: myData
  },
  computed: {
    n_movies(){
      return this.movies.length;
    },
  }
  ,methods: {
    changeN(){
      if(this.option_n_movies > this.n_movies) loadMovies(this.option_n_movies);
      if(this.option_n_movies < this.n_movies) {
        myData = myData.slice(0, this.option_n_movies );
      }
    },
  }
}).$mount('#app');

(option_n_movies is connected with a

v-model="option_n_movies" v-on:change="changeN"
to an input and should allow changing the number of items in the array)

While it almost works as intended, I suspect that there is a disconnect between app.$data.movies and myData at some point. This means that adding items to myData does not reflect in app.$data.movies.

The problem seems to arise when using slice(): Slicing myData does not reflect in app.$data.movies, leading to a loss of connection and making further additions ineffective.

I am wondering what mistake I might be making here. Are there alternative approaches to tackle this issue?

Answer №1

The issue lies in the fact that when you use slice(), it creates a new array without affecting the original one:

The slice() function generates a shallow duplicate of a section of an array into a fresh array object chosen from the starting position to the end position (excluding the end). The initial array remains untouched.

var myData = [1, 2, 3, 4, 5];
var myData2 = myData.slice(2)
console.log(myData)
console.log(myData2)

This means that your code is essentially doing this:

var myData = [1, 2, 3, 4, 5];
movies = myData
myData = myData.slice(2)

// myData and movies are not the same array
console.log(myData === movies)

To actually remove elements from the array, you should utilize splice().

var myData = [1, 2, 3, 4, 5];
movies = myData
myData.splice(0, 2)

// both arrays remain equivalent
console.log(myData===movies)

console.log(movies)

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

Merge multiple Javascript files into one consolidated file

Organizing Files. /app /components /core /extensions - array.js - string.js /services - logger.js /lib - core.js Core.js (function() { 'use strict'; an ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

How to utilize 'this' in a Vue template?

I'm feeling confused: I came across information stating that we can use this in Vue.js templates. But now I'm unsure about which one to use. I decided to experiment with some cases here: new Vue({ el: "#app", data: function() { return { ...

Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something? I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive: angular.js:12701 POST 500 (Internal Server Error ...

Learn how to toggle the display of a div using jQuery, just like the functionality on the popular website

Visit Mashable here Below is the script I am currently using: $(document).ready(function(){ $(".show_hide5").mouseover(function(){ $('.selected').removeClass('selected'); $(this).next().fadeIn("slow").addClass(&apo ...

What is the best way to implement the settimeout method in react?

I need assistance on how to effectively utilize the setTimeout() method in my code. Specifically, I am looking to trigger a click event on an element after a certain delay and execute a function afterwards. Here is the current implementation of my code: ...

Javascript: A Fun Game of Questions and Answers

When using JavaScript exclusively, I have an array consisting of four questions, four correct answers, and four incorrect answers. The use of arrays is essential to maintain order in the data. As each question is displayed, a random number is generated by ...

Discover the ins and outs of integrating YAML front matter into your destination directory path

I am looking to customize the path of my blog posts to include a fancy date format like /blog/2013/09/17 so that the links from my previous octopress blog remain intact. Within the YAML front matter on each markdown page, I have included the date informat ...

Discover the parent DOM element of a specified element using jQuery

When using jQuery, I am currently exploring methods to navigate through the DOM until it locates a specific selector. For instance: Consider this structure: <span data-type="contact" data-filter="4" id="buyer-lookup" class="uneditable-input contact-lo ...

Utilizing JSON for live population of search filter results

I'm currently developing a search function for my website that will sift through a JSON Object using regular expressions. My goal is to have the results displayed in real time as the user types, similar to how Google shows search suggestions. However ...

When attempting to create a build using npm run, an error with code ELIFECYCLE occurred despite successfully installing

I've been attempting to run the lodash library on my computer. You can find the library here on GitHub. I went ahead and forked the repository, then cloned it onto my system. I successfully installed all dependencies mentioned in the package.json fil ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Step-by-step guide to generating a Paypal Button using Vue 3 script setup

After going through the PayPal Developer Docs, I'm still struggling to understand how to integrate the PayPal Button into Vue.js. The code examples provided are unclear, and I can't determine if it's related to Vue 2, Vue 3, or even Angular. ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

Updating to the latest version of Next.js will result in a modification of the API path

I recently updated my app to the latest version of nextjs (13.1.6) and encountered a problem where all my requests are now failing. It seems that the URL I specified in the request creator, based on the ENV value, is being overwritten. .env file CONST NEXT ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

No control access origin header found on the request to Spring 5 WebFlux functional endpoints

I have scoured numerous resources in search of the perfect solution to my issue. In my opinion, I believe I have all the necessary components in place but I am unable to pinpoint where the problem lies. Utilizing spring 5 with WebFlux and functional endpo ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...