Having trouble with Javascript Array Push and Splice not functioning properly?

My goal is to replace the value "3" with "4" in the array. After this operation, only "1":"2" will remain in the array.

const array = [];

array.push({ "1": "2" })
array.push({ "3": "4" })


const index = array.indexOf(3);
if (index > -1) {
  array.splice(index, 1);
}
console.log(array)

Answer №1

When dealing with OBJECT values

If you are using indexOf with objects, it is important to compare them with the exact same object reference. You must have the identical reference to successfully remove it from the array where it was previously added.

Objects are compared based on references, while primitives are compared based on values. For further details, refer to How to determine equality for two JavaScript objects?

const array = [];
const obj = { '3': '4' };
array.push({ '1': '2' });
array.push(obj);

const index = array.indexOf(obj);
console.log(index);

When working with PRIMITIVE values

If you are dealing with an array of primitive values, you can safely use indexOf because primitives are compared based on their values as shown below:

const array = ['1', '2', '3'];
console.log(array.indexOf('3'));


1) An alternative approach is to use findIndex with hasOwnProperty to achieve a similar result. Credits to pilchard for this suggestion.

const array = [];

array.push({ '1': '2' });
array.push({ '3': '4' });

const index = array.findIndex((o) => o.hasOwnProperty('3'));
if (index > -1) {
  array.splice(index, 1);
}
console.log(array);

2) Another option is to use findIndex to locate the index of an object that contains 3 as a key.

const array = [];

array.push({ '1': '2' });
array.push({ '3': '4' });

const index = array.findIndex((o) => Object.keys(o).some((k) => k === '3'));
if (index > -1) {
  array.splice(index, 1);
}
console.log(array);

Answer №2

To implement the Array.pop() method effectively, you can follow this example:

let myArray = [];

myArray.push({ a: 'b' });
myArray.push({ x: 'y' });
myArray.pop();

console.log(myArray);

Answer №3

After adding both elements to the array, the structure would be as follows:

[  {"1":"2"}, {"3":"4"} ]

As a result, when using the indexOf method, it will not return anything.

To achieve the desired outcome, consider utilizing an object and using delete to eliminate any unwanted properties. For example:

const obj = {}

obj["1"] = "2";
obj["3"] = "4"

console.log("original obj : ", obj)

delete obj["3"];

console.log("filtered obj : ", obj)

Answer №4

filter the elements. When an element's key matches your specified key, it will not be included in the filtered array.

const arr = [];

arr.push({ 1: '2' })
arr.push({ 3: '4' })

function excludeElement(arr, k) {
  return arr.filter(obj => {
    return Object.keys(obj)[0] !== k;
  });
}

console.log(excludeElement(arr, '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

When using json_decode with $_POST, it may return NULL

Having difficulty with json_decode and a valid JSON being sent via $_POST. Here's the JSON object, stored in the "inventory" variable: [{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"}, {"item_name":"Brown Shoes","item_desc": ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

Effective techniques for unit testing in Vue.js

Here's a question that's been on my mind: when it comes to unit testing in Vue.js, there are several different packages available. Vue Test Utils Vue Jest Vue Cypress For enterprise projects, which of these options would be considered best ...

When using an `if` statement in CSS to determine if the value of `left` is

Is there a way to trigger an event only when the object reaches a specific percentage of its left position? I am trying to achieve this using jQuery with the .css() method. Here is what I have so far: HTML: <div id="midDiv"><img ..../></di ...

Pictures squeezed between the paragraphs - Text takes center stage while images stand side by side

I'm struggling to figure out how to bring the text between the two images to the front without separating them. The images should be positioned next to each other with a negative square in-between, and the text within this square should be centered b ...

Highcharts displays data with the fourth y axis but doesn't include labels for it

I'm facing an issue with displaying all the labels on my chart. I have 4 series plotted and decided to add two y-axes on each side of the graph, but the labels for the last series named "Stuff Data" are not showing up correctly. Instead, it seems to b ...

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Is there a method to delay the loading of a webpage until an image has fully loaded (preloading)?

How can I ensure that an image used in a preloader is loaded before the other contents on my website? <div class="overlay" id="mainoverlay"> <div class="preloader" id="preloader"> <img src="images/logo128.png" id="logo-p ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

In what part of my code should I integrate the .sort() method?

I am working on rendering a list of items in alphabetical order to the browser. I have previous experience using .sort() in other scenarios, but I am unsure about where to place it in this particular situation. In my current code, I initially placed the . ...

Exploring the retrieval of data from .find within a JSON object using Node.js

In my custom database setup, which mirrors a collection in MongoDB containing JSON objects. export const roles = [ { _id: "870c4350-3cf5-4f35-8429-513bd86c6734", programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968", profileId: "3cbaadcf-41e1-42 ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...

Getting the URL of a CSS background image in NodeJS and Express: A step-by-step guide

I've recently learned that using getComputedStyle in a Node environment is not possible due to it being a browser-specific behavior. Despite this, I am still interested in retrieving all background image URLs within Node and downloading them as shown ...

Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

Refresh a row in real-time by utilizing a modal with JavaScript or jQuery

Is there a way to dynamically edit and update a previously submitted row (category name) in a table? I am able to edit a row by clicking on an edit button and displaying a modal with the current value. However, I am facing a challenge when trying to submit ...