When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have:

var hdr = ("name", "date", "start_time", "selling_item", "total_call", 
           "end_time", "ad_num", "area", "order_num");
//this data comes from the database

Now, I need to rename these array elements according to proper naming conventions. So, this is my approach:

renameTableHdr(hdrs){
        var handler = hdrs;

        for(var a = 0; a<hdrs.length; a++){
            // console.log(hdrs[a]);
            var itm = "";
            if(hdrs[a] === 'name'){
                itm = "Name";
            }
            if(hdrs[a] === 'ad_num'){
                itm = "Ad Number";
            }
            //and so on for all other elements

            if(handler.indexOf(hdrs[a]) >= 0){
                handler.splice(handler.indexOf(hdrs[a]),1);
            }
            this.tempTblHdr.push(itm);
        }
    },

When I don't use splice, the output seems correct as expected. However, when I use splice, it does not work properly.

Output without using splice

(9) ["Ad Number", "Date", "Order Number", "Start Time", "Name", "Area", "Selling Item", "End Time", "Total Call", __ob__: Observer]

Using Splice

(5) ["Ad Number", "Order Number", "Name", "Selling Item", "Total Call", __ob__: Observer]
//missing 4 data elements

I'm removing certain items from handler to ensure they are in the correct naming convention. The intention is to rename them without altering their indexes. Am I correctly implementing the splice method here?

Answer №1

If you want to remove an item from an array, it is recommended to do it in reverse order. This is because the index of the items in the array keeps changing even after deletion.

For example:

let array = ["a", "b", "c", "d"];
for (let i = 0; i < array.length; i++) {
  console.log(array.splice(i, 1));
}

During the first iteration, when i is 0, it removes "a". In the second iteration, with i as 1, it skips "b" and removes "c". On the third iteration, since the array is now ["b", "d"], it stops before removing anything else.

To avoid skipping elements when removing items, go through the array in reverse order. Make sure to add new items using unshift method for proper indexing:

renameTableHdr(hdrs){
    var handler = hdrs;

    for(var a = hdrs.length-1; a>=0; a--){
      // Logic for renaming headers
      if logic condition{
        // Rename header item
      }
      
      // Removing item from array
      if(handler.indexOf(hdrs[a]) >= 0){
        handler.splice(handler.indexOf(hdrs[a]),1);
      }
      this.tempTblHdr.unshift(itm);
    }
},

Answer №2

One approach to simplifying the translation without using for loops or mutating the data is as follows:

function translateHeaders(headers) {
  const translations = {
    name: 'Name',
    ad_num: 'Ad Number',
    date: 'Date',
    order_num: 'Order Number',
    start_time: 'Start Time',
    area: 'Area',
    selling_item: 'Selling Item',
    end_time: 'End Time',
    total_call: 'Total Call',
    'things with spaces': 'Translates fine'
  };
  return headers.map((header) => translations[header] || "");
}

console.log(
  translateHeaders([
    'name',
    'date',
    'start_time',
    'selling_item',
    'total_call',
    'end_time',
    'ad_num',
    'area',
    'order_num',
    'XXXXXXXXXXXXXXXXXXXXXXXXXX',
    'things with spaces',
  ]),
);

Answer №3

It is important to iterate backwards when removing an item from an array, as shown in the code example below:

   removeItemFromArray(items){
        var arr = items;

        for(var i = items.length - 1; i >= 0; i--){
            // Code logic for removing item
        }
    }

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

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

res.send No data being transmitted - in the realm of Express.js

I'm currently developing a calculator app using Express.js, but I seem to be encountering an issue with the res.send Method as I am not getting any response. My expectation is for my webpage to display the sum from the calculator.js file. Nodemon is a ...

How can I use an API in Vue to rearrange the order of an array?

I have an array of objects that I need to update the display order for by sending an API request to the database. How do I include the order_position in the body of the API request? I plan to trigger the API request upon clicking the confirm button. Do I n ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

Make sure the inputs in separate table data cells are lined up in

I need help aligning two input fields in separate td elements to be on the same line. The issue I am encountering is that when an input is added to a td, it covers up any text within the td. https://i.stack.imgur.com/c7GiQ.png There are two scenarios: I ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

When using React hooks forms, setting default values from a reduced array does not automatically populate the form. However, manually entering the same object into the form does

As I work with react hooks forms, I am facing a challenge in setting default values for a form generated by mapping over an array to output the inputs. After reducing the array into an object format like {name0:"fijs",name1:"3838"...}, manually passing thi ...

Troubleshooting Issue: XMLHttpRequest Incompatibility with Internet Explorer

I'm having an issue with the script below. It works fine on Firefox and Chrome but doesn't seem to work on IE. I've tried various solutions, including lowering the security settings on my browser, but it still won't work. function se ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...

Node js Express js token authentication: unraveling the implementation complexities

After extensive research on authentication methods for nodejs and express js, I find myself at a crossroads. So far, the most helpful tutorial I've found on sessions is this one. I am working with the mean stack and my main goal is to provide users ...

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

Steps to remove the smallest number from an array: if there are multiple smallest numbers, remove the first one

I am currently working on a script that takes an array of random numbers as input. I have successfully implemented code to remove the lowest number in the array, but I'm facing an issue when there are multiple occurrences of this number. How can I ens ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Troubleshooting JavaScript Oscilloscope: resolving audio playback problems

I am exploring JavaScript for the first time and came across an interesting oscilloscope example on this GitHub page. It seemed quite easy to follow initially, but I am facing an issue with audio playback. Although the HTML5 audio element loads the audio f ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...

"Utilizing Axios to convey JSON data into Vue Js: A Step-by-Step Guide

After saving my JSON data in a JS file for Vue, I encountered an issue with accessing it and getting my HTML v-for condition to work properly. The method described in the Vue.js documentation didn't help me fetch and execute the JSON data. Could someo ...

Using SCSS variables in TypeScript inside a Vue project

Has anyone had experience with importing SASS (scss) variables into JavaScript in a TypeScript Vue 3 project? // @/assets/styles/colors.scss $white: #fff; // @/assets/styles/_exports.scss @import "./colors.scss"; :export { white: $white; } <templat ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...