What is the most effective method for identifying all deleted or inserted items in an original array using Javascript?

When the app is not changed, I have a list of numbers called originalArray. After making some modifications, I now have modifiedArray where some items were inserted or deleted from originalArray. I've written a function to identify all the items that were deleted or inserted from the originalArray.

var modifiedArray = [1,3,5,6,7,8,9,10,11];
var originalArray = [1,2,3,4,5,6];
var insertedArray = [];
var deletedArray = [];

function findChanges() {
    for(var i = 0; i < originalArray.length; i++){
        if(modifiedArray.indexOf(originalArray[i]) == -1){
            deletedArray.push(originalArray[i]);
        }
    }

    for(var i = 0; i < modifiedArray.length; i++){
        if(originalArray.indexOf(modifiedArray[i]) == -1){
            insertedArray.push(modifiedArray[i]);
        }
    }
}

Do you think this is the most efficient way to identify all the items that were deleted or inserted from the original array?

If you have any other suggestions, please let us know.

Thank you very much.

Answer №1

var modifiedArray = [1,3,5,6,7,8,9,10,11];
var originalArray = [1,2,3,4,5,6];

function findDifferences(a,b){
return a.filter(function(x) { return b.indexOf(x) < 0 })
}

var insertedValues = findDifferences(modifiedArray, originalArray);
var deletedValues = findDifferences(originalArray, modifiedArray);

alert("Inserted: " + JSON.stringify(insertedValues));
alert("Deleted: " + JSON.stringify(deletedValues));

You may also leverage the lodash library. This library offers various functions for handling arrays/objects.

var modifiedArray = [1,3,5,6,7,8,9,10,11];
var originalArray = [1,2,3,4,5,6];
var insertedValues = _.difference(modifiedArray, originalArray);
var deletedValues = _.difference(originalArray, modifiedArray);

Answer №2

One method to consider is using a hash table to keep track of the deleted items by using them as remainders.

An example implementation in JavaScript:
var modifiedArray = [1, 3, 5, 6, 7, 8, 9, 10, 11],
    originalArray = [1, 2, 3, 4, 5, 6],
    insertedArray = [],
    deletedArray = [],
    hash = Object.create(null);

originalArray.forEach(function (a) {
    hash[a] = {value:a};
});

insertedArray = modifiedArray.filter(function (a) {
    var r = !hash[a];
    if (hash[a]) {
        delete hash[a];
    }
    return r;
});

deletedArray = Object.keys(hash).map(function (k) { return hash[k].value; });

console.log(insertedArray);
console.log(deletedArray);

Answer №3

We apologize for the inconvenience, this solution may incur higher costs (Special thanks to zerkms for the feedback)

Your algorithm iterates through both arrays, but a more efficient approach might be to only iterate through the original array:

For each element in the original array:

  • If it exists in the modified array > remove it from both arrays
  • If it does not exist in the modified array > leave it unchanged

After completing this process, the modified array will contain only elements that were added (not in the original array) and the original array will only include elements that were deleted (not in the modified array).

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

Adjusting the height of the Sencha Touch container to accommodate its content

In Sencha Touch, I have a view that generates a popup box from the right when a button in the bottom toolbar is clicked: Ext.define('TheApp.view.PopupTablet',{ extend: 'Ext.form.Panel', xtype: 'popupbox', confi ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

Create a CSS popup alert that appears when a button is clicked, rather than using

Is there a way to customize CSS so that the popup alert focuses on a button instead of just appearing like this? https://i.sstatic.net/r25fd.jpg I have implemented this type of validation for a text box: <div class="form-group"> <label class="co ...

Tips for setting up a webpacked vue.js application with an express/koa backend!

Struggling with setting up a vue.js project for easy debugging in combination with a koa server? The cross-env NODE_ENV=development webpack-dev-server --open --hot command from the webpack-simple generated configuration looks promising, but how should it b ...

How can I retrieve an empty object from the database using Angular 5?

Hey there! I'm facing a little issue that I need help solving. I asked a question before when things weren't clear, but now they are (you can find the previous question here). I'll share my code and explain what I want to achieve shortly. H ...

How to use the handleChange() function in React with various state properties

Explaining a bit about the handleChange function, which takes the name of the state element to be associated with it. Is there a specific reason why it has to be structured like this: handleInputChange(property) { return e => { this.setSta ...

Dealing with Array Splicing Issues in Angular

Being fairly new to the world of AngularJS, I suspect that I am just making a simple mistake. My goal is to splice the cardTypes array at the var newCard = cardTypes.shift(); line rather than using .shift() so that I can consider my ng-repeat index. Whil ...

"Exploring the possibilities of integrating the Twitter API with

Currently, I am attempting to access my most recent tweet from Twitter using https://github.com/jdub/node-twitter I am interested in setting a variable, modifying that variable within a function, and then utilizing it again outside of said function. Is th ...

The HTML5 video will continue playing indefinitely as long as its readyState remains at 4

In my efforts to develop a personalized HTML5 video player that can handle live streaming, recording of live streams, and playing regular video files, I have run into an issue with creating a custom seeking bar. To achieve this, I implemented the following ...

I attempted to utilize certain CSS properties, only to find that they were not being applied due to conflicts with Bootstrap's own CSS. I'm unsure what I should do next

click here for image .container, .container-fluid, .container-lg, .container-md, .container-sm, .container-xl, .container-xxl { --bs-gutter-x: 1.5rem; --bs-gutter-y: 0; width: 100%; **padding-right: calc(var(--bs-gutter-x) * .5);** **pa ...

Set default selected value for dropdown list using radio buttons

Could anyone provide guidance on how to reset a dropdown list value using a radio button selection? Specifically, I need the dropdown list to reset to its default "selected" option when a particular radio button is clicked. Any recommended approaches usin ...

Automated method for triggering button clicks on a webpage using JavaScript with a tailored combination of unique tag and class name

Currently, I am exploring methods to automatically trigger a button click on a webpage with a specific tag and class. My approach involves using Tampermonkey (Javascript userscripts) to accomplish this task. Referencing the image of the CSS/HTML elements r ...

Bootstrap modal fails to appear on screen

Using PHP, I generate a link from the controller. The link is stored in $retailer["url"] as 0125myimage.jpg <a onClick="crop('.$retailer["url"].')" data-target="#styledModal3" href="#" class="fa fa-edit lupa"></a> Here is my JavaSc ...

When the user clicks, display one div and conceal the others

https://codepen.io/leiacarts/pen/PoqRxNZ I need assistance with two specific tasks related to my website layout. Firstly, I am struggling to ensure that images displayed in the red sections remain constrained and automatically resize within the content di ...

The module could not be found because there was an error: Unable to locate '@mui/icons-material/AddCircle', despite the fact that @mui/icons-material has been installed

When working with the IR compiler in Kotlin JS, I encountered an issue. The error message reads: Module not found: Error: Can't resolve '@mui/icons-material/AddCircle' Even though @mui/icons-material is already installed, the error persist ...

Refresh i18next translations without needing to reinitialize

Currently utilizing I18next alongside the Backend plugin, I am looking to find a way to prompt the Backend plugin to refresh translations for a specific language/namespace. This issue was previously raised regarding the nodejs plugin two years ago as see ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Tips on maintaining the content of an element within a directive template

I'm currently facing an issue with adding the ng-click directive to a button. Here's my HTML: <button class="btn">clicky</button> This is the directive I am using: angular.module('app').directive('btn', function ...

Adjust mesh tessellation level using scroll control

On this page (), you can see how the meshes forming the text continuously come together and then separate in a loop, as demonstrated in the source code here: https://github.com/mrdoob/three.js/blob/dev/examples/webgl_modifier_tessellation.html. I am inter ...

Filtering arrays using Vue.js

I have developed a sample e-commerce website to showcase various products to potential customers. The website boasts features like filters, search functionality, and sorting options to enhance the user experience. However, I've encountered an issue sp ...