JavaScript puzzle: Deciphering the differences between objects, arrays, and arrays containing objects

Having a rough coding day today. I can't seem to figure out why this code on fiddle isn't behaving as expected.

var masterList = new Array();
var templates = new Array();
templates.push({"name":"name 1", "value":"1234"});
templates.push({"name":"name 2", "value":"2345"});
templates.push({"name":"name 3", "value":"3456"});
templates.push({"name":"name 4", "value":"4567"});
templates.push({"name":"name 1", "value":"5678"});
templates.push({"name":"name 2", "value":"6789"});
templates.push({"name":"name 3", "value":"7890"});
templates.push({"name":"name 4", "value":"8901"});


var addUnique = function(thatObj) {
    var newList = new Array();

    if ( masterList.length == 0 ) {
        // add the first element and return
        masterList.push(thatObj);
        return;
    }

    for (j=0; j<masterList.length; j++) {
        if (masterList[j].name != thatObj.name) {
            newList.push(thatObj);
        }
    }

    // store the new master list
    masterList = newList.splice(0);
}

for (i=0; i<8; i++) {
  addUnique(templates[i]);
}

console.log(masterList);
console.log(masterList.length);

In my (humble) opinion, it should iterate through the templates array, populate the masterList with each element of the templateArray, but only result in 4 elements in the master array, as those with the same name should be replaced rather than copied into the intermediate array. However, I'm only seeing one entry in masterList.

Where are the good old days of strongly typed languages and pointers? Sigh. It's frustrating not being able to grasp the mess JavaScript is creating (well, maybe I'm the one making the mess) but I blame JS for not understanding me...

Answer №1

The scope of newList is within the addUnique function, which gets called 8 times in a loop. Every time this function is executed, a new value is assigned to masterList (masterList = newList.splice(0);), resulting in only the final value being displayed in the console.log(masterList).

To resolve this issue, you can refer to the corrected version of your code on this fiddle: http://jsfiddle.net/vZNKb/2/

var addUnique = function(thatObj) {
    if ( masterList.length == 0 ) {
        // Add the first element and then exit
        masterList.push(thatObj);
        return;
    }

    var exists = false;
    for (var j = 0; j < masterList.length; j++) {
        if (masterList[j].name == thatObj.name) {
            exists = true;
            break;
        }
    }

    if (!exists) {
        masterList.push(thatObj);
    }
}

Answer №2

Ensure your loop in the addUnique function iterates through all elements before adding a new one if no matches are found.

relevant excerpt


let isMatchingRecord = false;
for(let index=0; index<mainArray.length; index++) {
    if (mainArray[index].value === currentObject.value) {
        isMatchingRecord = true;
        break;
    }
}
if (!isMatchingRecord) updatedArray.push(currentObject);

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

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

Troubleshooting Rails 4: Handling a 404 Not Found Error When Making an AJAX Call to a

After spending about an hour trying to figure this out, I am still stuck... The action in my oferts_controller.rb file looks like this: def update_categories @categories = Category.children_of(Category.find(params[:categories])) respond_to ...

When working with arrays in a programming loop, is it better to assign the value to a variable or access it directly?

When facing a complex for loop with lots of operations, what is the most efficient way to iterate through it? for ($i = 0; count($array) > $i; $i++) { $variable = $array[$i]; $price = $variable->price; OR $price = $array[$i]->price; } T ...

Is it possible to utilize splice and push methods on a computed array in VueJS?

Is it possible to programmatically change a computed array? Perhaps by splicing an item from an array and pushing it to another position? list_array = [{list_id: 1, status: 'good', data: {item_id: 1, event: 'jumping'}] The code for sp ...

Working with Symfony to insert array elements into a database using ORM concepts

I received a file that contains my list of arrays, which you can access here. In order to populate two fields in the database (type and data field), I have successfully returned all array objects as a string for the data field. However, I am struggling wi ...

Updating jQuery event behaviors based on the value of .html( 'string' )

Visit this link for more information. Feel free to modify the heading if you believe it needs improvement. General I manage a multilingual WordPress website with dynamic menu and navigation controlled through the WordPress admin panel. The multilingual ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...

Backbone causes a sudden influx of unexpected AJAX requests

I included the fetch URL with a deferred method, expecting it to only make one remote AJAX request. However, I noticed that it is being called three times when the page loads. Does anyone know how to resolve this issue? Thank you JS Scripts var Commen ...

Error: The function coolArr.printArray is not defined in the npm package being imported

My custom package contains an index.js file with the following code: module.exports = class CoolArray extends Array { printArray() { console.log(this); } } After transpiling the code using es2015 syntax with Babel, I connected the package to my te ...

Filter search results using selected region from dropdown menu

I have been attempting to retrieve the value from a dropdown list and customize the search functionality specifically for the selected field. The client should only be able to search within the chosen zone in the dropdown. I have been searching for a solut ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Is it common for Google Chrome console snapshots to have a prolonged idle time?

I noticed in Google Chrome console snapshot that my JavaScript code has a long "Idle" time. I'm not sure if this is normal. Attached is a screenshot for reference: https://i.stack.imgur.com/k0mkp.png Could this extended "Idle" time be attributed to ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Unable to find module reference "three" at 137

Returning to an older project, I realized that nothing was loading. When I checked the console log, this is what I found: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". In my ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

Function executed prior to populating $scope array

I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init, the $scope.bookings array is not yet populated, resulting in empty data. My objective is: Retrieve all book ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Difficulty loading AJAX with autocomplete feature. Any suggestions?

I have created a jQuery autocomplete feature that works correctly, but when the value is removed using the Backspace key, the 'LOADING...' message remains visible instead of hiding. How can I make it so that after removing the value with the Back ...