Home > Software engineering >  How to remove value from an array using javascript
How to remove value from an array using javascript

Time:06-20

Trying to remove a particular value from an array. But not able to remove because the array is like this

  var cardValue = {
      options: ['Bus', 'Car', 'Motor'],
    };

So, How to remove a value for that array?

const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS Starter</h1>`;

var cardValue = {
  options: ['Bus', 'Car', 'Motor'],
};

const index = this.cardValue.options.indexOf('Bus');
if (index > -1) {
  this.cardValue.options.splice(index, 1);
}

console.log(cardValue); // Car, Motor
<div id="app"></div>

Demo: https://stackblitz.com/edit/js-a1jxhx?file=index.js

CodePudding user response:

You should not use this before accessing cardValue object

var cardValue = {
  options: ['Bus', 'Car', 'Motor'],
};
    
const index = cardValue.options.indexOf('Bus');
if (index > -1) {
  cardValue.options.splice(index, 1);
}

console.log(cardValue); // Car, Motor

CodePudding user response:

const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS Starter</h1>`;

var cardValue = {
  options: ['Bus', 'Car', 'Motor'],
};

const index = this.cardValue.options[0];


console.log(cardValue); // Car, Motor
<div id="app"></div>

CodePudding user response:

var list = ["bar", "baz", "foo", "qux"];

list.splice(0, 2);

// Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].

  • Related