How do I get it to stop adding new objects to an array if an object already exists?

Issue

The code loops 2 times. The first loop should add {} to the empty testArr array and the second loop should change the item at testArr[0] to say "new object". After each loop, the length of the array should not
change.

Question

How do I get it to stop adding new objects to an array if an object already exists? Emtpy object or not, it still does the same thing? Is it just that Js treats objects a certain way?

I’m specifically trying to work with objects, but if this doesnt work is there a simple solution?

Code

testArr = [];

function test_arr_includes() {
    if (testArr.includes({}) === false) {
        testArr.push({})
    } else {
        testArr[0] = "new object"
    }
}

for (let i = 1; i <= 2; i++) {
    // update({ id: "cabbage" });
    test_arr_includes();
    console.log(testArr)
}

This is what I’m actually trying to work on

When you compare objects in JavaScript (which is what includes is doing), they compared by reference (location in memory) rather than by value (what the object looks like).
{} == {} is false.

As mentioned by @ArielLeslie above, you con’t directly compare the objects the way you’re doing… I’ve made some modifications to your code from github and added comments inline to significantly simplify your code

const scan_arr = [];

const scan = (id, lbs = undefined) => {
    return { id: id, lbs: lbs };
};

const update = item => {

    // no need for all this...
    // let count;
    // item.lbs === undefined ? (count = 1) : (count = item.lbs);
    // item.count = count;
    // delete item.lbs;

    // above 4 lines can simply be replaced with following line
    item.count = item.count || 1;
    // seems like you need lbs to only keep track of count.
    // So it is not required and can totally be determined by using count


    // find method will give you the object that matches the condition.
    // undefined otherwise
    const existingItem = scan_arr.find(i => i.id === item.id);
    
    if(existingItem) {
      // since now you have reference to the actual item in the array,
      // any changes you make to it will be reflected in your array.
      existingItem.count++; 
    } else {
      scan_arr.push(item);
    }
};

// exports
module.exports = {
    scan: scan,
    update: update,
    scan_arr: scan_arr
};
2 Likes

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

This is not an FCC challenge. This is something I was working on by myself and what he gave me was exactly what i wanted.