What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than index. This is because each page only displays five values, and removing by index would affect other pages as well due to consistent indexing across pages. Is there a method besides using splice to achieve this, or is there another solution available?

  totalArray = [
     {id: 1, city: 'LONDON'},
     {id: 2, city: 'PARIS'},
     {id: 3, city: 'NEW YORK'},
     {id: 4, city: 'BERLIN'},
     {id: 5, city: 'MADRID'},
     {id: 6, city: 'ROME'},
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ]      

   selectionArray = [
     {id: 6, city: 'ROME'},
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ]

  selectionArray.forEach((item, i) => { 
      totalArray.splice(item.id, 1);
  });

Answer №1

If you're looking to make changes to the original array itself, here's a solution that takes this approach:

  • First, get the id of each item in the selectionArray using array.forEach.
  • Then, locate the element with the corresponding index in the total array.
  • Get its index and remove the element from the array.

This solution closely mirrors what you attempted in your own code.

const totalArray = [
     {id: 1, city: 'LONDON'},
     {id: 2, city: 'PARIS'},
     {id: 3, city: 'NEW YORK'},
     {id: 4, city: 'BERLIN'},
     {id: 5, city: 'MADRID'},
     {id: 6, city: 'ROME'},
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ],   
  selectionArray = [
     {id: 6, city: 'ROME'},
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ];

selectionArray.forEach(({id: uid}) => {
  totalArray.splice(
    totalArray.indexOf(totalArray.find(({id}) => uid === id)),
    1
  );
});
console.log(totalArray);

Keep in mind that if the elements in both arrays originate from the same source, you can simply use indexOf.

Answer №2

Perhaps there could be a more efficient solution. Essentially, this code snippet loops through both arrays, and if the id matches, it removes that element from the first array.

mainArray = [
     {id: 1, city: 'LONDON'},
     {id: 2, city: 'PARIS'},
     {id: 3, city: 'NEW YORK'},
     {id: 4, city: 'BERLIN'},
     {id: 5, city: 'MADRID'},
     {id: 6, city: 'ROME'},
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ]      

   subArray = [
     {id: 1, city: 'LONDON'},     
     {id: 7, city: 'DUBLIN'},
     {id: 8, city: 'ATHENS'},
     {id: 9, city: 'ANKARA'},
     {id: 10, city: 'MOSCOW'},
  ]
  
  for (index in mainArray){
    
    for (subIndex in subArray){
      if (mainArray[index].id === subArray[subIndex].id){
        mainArray.splice(index,1)
      }
    }
  }
  console.log(mainArray)

Answer №3

If you want to remove items from an array, you can utilize the Array#filter method. By combining this with Array#every, you can ensure that the item is not present in the removal array.

const totalArray = [
  { id: 1, city: "LONDON" },
  { id: 2, city: "PARIS" },
  { id: 3, city: "NEW YORK" },
  { id: 4, city: "BERLIN" },
  { id: 5, city: "MADRID" },
  { id: 6, city: "ROME" },
  { id: 7, city: "DUBLIN" },
  { id: 8, city: "ATHENS" },
  { id: 9, city: "ANKARA" },
  { id: 10, city: "MOSCOW" }
];

const selectionArray = [
  { id: 6, city: "ROME" },
  { id: 7, city: "DUBLIN" },
  { id: 8, city: "ATHENS" },
  { id: 9, city: "ANKARA" },
  { id: 10, city: "MOSCOW" }
];

const remainingArray = totalArray.filter(city =>
  selectionArray.every(selCity => selCity.id !== city.id)
);

console.log(remainingArray);

The filter function iterates through each item and executes a callback. If the callback returns true, the item is kept. If it returns false, the item is removed. The resulting array contains the remaining values.

The every function also loops through each item in the array. It returns true if the callback evaluates to true for all items, otherwise it returns false.

In this scenario, we are checking for each city in

totalArray</code to verify that its <code>id
is not found in every city of selectionArray.

Answer №4

const mainCities = [
   {id: 1, city: 'LONDON'},
   {id: 2, city: 'PARIS'},
   {id: 3, city: 'NEW YORK'},
   {id: 4, city: 'BERLIN'},
   {id: 5, city: 'MADRID'},
   {id: 6, city: 'ROME'},
   {id: 7, city: 'DUBLIN'},
   {id: 8, city: 'ATHENS'},
   {id: 9, city: 'ANKARA'},
   {id: 10, city: 'MOSCOW'},
];  

const selectedCities = [
   {id: 6, city: 'ROME'},
   {id: 7, city: 'DUBLIN'},
   {id: 8, city: 'ATHENS'},
   {id: 9, city: 'ANKARA'},
   {id: 10, city: 'MOSCOW'},
];

// Using splice
// We iterate over the "selectedCities" and use .findIndex() to locate the index of each object.
const result_splice_final = [ ...mainCities ];
selectedCities.forEach( selectedCity => {
  const index_in_mainCities = result_splice_final.findIndex( main => main.id === selectedCity.id );
  result_splice_final.splice( index_in_mainCities, 1 );
});
console.log( 'RESULT_SPLICE_FINAL' );
console.log( result_splice_final );

// Using .filter();
// We extract all the selected ids and then .filter() the "mainCities" to eliminate
// all items with an id found inside "selected_ids"
const selectedIds = selectedCities.map( selected => selected.id );
const result_filtering = mainCities.filter( main => !selectedIds.includes( main.id ));
console.log( 'RESULT_FILTERING' );
console.log( result_filtering );

// Using .find()
// Similar to using .filter(), but instead of extracting the ids beforehand, we loop over the "selectedArray" with .find()
const result_find_city = mainCities.filter( main => {
  return !selectedCities.find( selected => selected.id === main.id );
});
console.log( 'RESULT_FIND_CITY' );
console.log( result_find_city );

const json_splice_final = JSON.stringify( result_splice_final );
const json_filtering = JSON.stringify( result_filtering );
const json_find_city = JSON.stringify( result_find_city );
console.log( 'All results are identical:' );json_find_city && 
console.log( json_splice_final === json_filtering && json_splice_final === json_find_city && json_filtering === json_find_city );

Answer №5

The quickest and most straightforward method is as follows:

const initialList = [
    { id: 1, city: 'LONDON' },
    { id: 2, city: 'PARIS' },
    { id: 3, city: 'NEW YORK' },
    { id: 4, city: 'BERLIN' },
    { id: 5, city: 'MADRID' },
    { id: 6, city: 'ROME' },
    { id: 7, city: 'DUBLIN' },
    { id: 8, city: 'ATHENS' },
    { id: 9, city: 'ANKARA' },
    { id: 10, city: 'MOSCOW' },
]

const selectedItems = [
    { id: 6, city: 'ROME' },
    { id: 7, city: 'DUBLIN' },
    { id: 8, city: 'ATHENS' },
    { id: 9, city: 'ANKARA' },
    { id: 10, city: 'MOSCOW' },
];

const selectedIds = selectedItems.map(({ id }) => id);
const remainingItems = initialList.filter(({ id }) => !selectedIds.includes(id));
console.log(remainingItems);

Answer №6

To find the index of a value in JavaScript, you can use the following code snippet:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = fruits.indexOf("Apple");

Once you have the index, you can remove that item from the array like this:

fruits.splice(index, 1);

If you need more information, you can check out this resource:

Love2Dev Removing Array Items By Value Using Splice

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

Ensure that the file exists before including it in the $routeProvider template for ng-include

Using Angular routes, I have set up a system where the slug from the URL determines which file to load. The code looks like this: $routeProvider.when("/project/:slug", { controller: "ProjectController", template: function($routeParams){ return & ...

I'm unable to resolve the issue regarding the message "Property or method is not defined on the instance but referenced during render."

I have a good grasp on what the issue is (the inputs I'm trying to v-model aren't declared), but for some reason, I can't resolve it (or figure out how to) even after studying other posts with the same problem. After comparing my code with ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

The responses for several HTTP POST requests are not being received as expected

I am facing a challenge in retrieving a large number of HTTP POST requests' responses from the Database. When I try to fetch hundreds or even thousands of responses, I encounter issues with missing responses. However, when I test this process with onl ...

Building XML using PHP with relatively extensive information stored in JavaScript

Similar Question: XML <-> JSON conversion in Javascript I have a substantial amount of data stored in JavaScript that I need to convert into an XML file on the PHP server. The process of transforming the data into a JSON object, sending it to PH ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

The "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

Encountering a popup_closed_by_user error while attempting to test Google OAuth within my web application

Currently, I am working on integrating Google login into my web application using AngularJS. Whenever the popup opens up for logging into my Google account or selecting an existing account, I encounter an issue where the popup closes with an error message ...

Newbie's Guide - Building React/React-Bootstrap JavaScript Components Post Linking CDNs in index.html

Exploring Glitch hosting for a React/React-Bootstrap website as part of my web development training. Although these tools are new to me, I have years of experience as a developer. Successfully linked React, React-Dom, Babel, and React-Bootstrap CDN's ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

Discover the myriad of possibilities created by combining arrays

I am working on a code snippet that aims to generate an array containing all possible combinations between two or more arrays. However, I am encountering a specific issue. getCombn(arr: string | any[], pre?: string | undefined) { pre = pre || ' &a ...

Using JavaScript, add a complex JSON record to a JSON variable by pushing it

I have been attempting to insert a complex JSON data record into a JSON variable using the following code: var marks=[]; var studentData="student1":[{ "term1":[ {"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]}, {"Work":[{"obtained":"13"," ...

Aggregate data by various categories and compute a total sum

I developed a recipe creation tool using Laravel 5.2. With this application, users can include ingredients in their recipes, sometimes duplicating ingredients depending on their use. Currently, I am working on a feature that enables users to generate a P ...

Navigate audio tracks with JavaScript

I'm currently facing an issue with using a button to switch between two audio tracks being played in the browser. The method I have implemented switches to the second track, but it doesn't change the audio that is played afterward - instead, it s ...

In case the desired property is not detected in the object, opt for an alternative property

Here is an example object: Object -> Content: <h1>some html</h1> Url : A url In the code below, I am checking if a specific URL exists in the given object: var checkURLInArray = function(url, array) { for(var i in array) { ...

Caution: It is important for each child to be assigned a distinct key - How to pass an array in

While following ReactJS tutorials on Scrimba, I came across a scenario where id props need to be passed in an array. import React from 'react'; import Joke from './components/Joke.js' import jokesData from './components/jokesDat ...

How can I execute a basic query in jQuery or JavaScript based on a selected value that changes

After successfully retrieving the dropdown selection value with alert(selectedString) in this scenario, I am now looking to utilize that value for querying a table using mysqli and PHP. What is the best approach for querying a database table based on the ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

How to modify the background color in Material Ui's datepicker?

Is there a way to customize the background color of my Material UI datepicker modal? To change the colors, you can use the createMuiTheme function from "@material-ui/core": const materialTheme = createMuiTheme({ overrides: { MuiPickersToolbar: ...