Explain Codes LogoExplain Codes Logo

Array.push() if does not exist?

javascript
prompt-engineering
best-practices
performance
Nikita BarsukovbyNikita BarsukovΒ·Sep 24, 2024
⚑TLDR

Prevent duplicates by using includes prior to push for uniqueness:

let array = [1, 2]; let itemToAdd = 2; // Check the array: if the item doesn't exist, push it; if it does, forget about it! πŸ˜† !array.includes(itemToAdd) && array.push(itemToAdd); // The array remains as it is [1, 2]

For object arrays, find or findIndex can be used to compare object properties prior to pushing:

let objectArray = [{ name: "Alice", text: "Hello" }]; let objectToAdd = { name: "Bob", text: "Hi" }; let exists = objectArray.find(obj => obj.name === objectToAdd.name && obj.text === objectToAdd.text); // Bob doesn't want to join a club that would have him! πŸ˜… if (!exists) { objectArray.push(objectToAdd); } // objectArray now joyfully welcomes the new objectToAdd

Quick Fix: Strings and Numbers Arrays

Exclude Dupes with Ease

Directly utilize includes or indexOf to check for the presence of an item (standard for strings or numbers) before pushing.

// If the itemToAdd isn't playing hide-and-seek in the array, let's push! if (!array.includes(itemToAdd)) { array.push(itemToAdd); }

The Novelty of Uniqueness

Switch to using a Set to keep your array unique. You can recklessly add items without worry for duplicates.

let uniqueSet = new Set(array); uniqueSet.add(itemToAdd); // If the item exists, the Set just gives a shoulder shrug 😏 array = [...uniqueSet]; // Convert back to array and voila!

Dealing with Object Arrays

Sherlock Holmes-ing Properties

To ensure there are no duplicate objects, property comparison comes to the rescue in arrays of objects.

// If the objectToAdd isn't 'name' - 'text' twinning with an existing object, we push! if (!objectArray.some(obj => obj.name === objectToAdd.name && obj.text === objectToAdd.text)) { objectArray.push(objectToAdd); }

Reusable Code? Yes Please!

Encapsulate the logic into a 'pushIfNotExist' function for easy reusability.

// Good developers repeat themselves, the best ones write a function to do so πŸ˜‚ function pushIfNotExist(array, element, comparer) { if (array.some(el => comparer(el, element)) === false) { array.push(element); } } // Usage with custom comparer function pushIfNotExist(objectArray, objectToAdd, (a, b) => a.name === b.name && a.text === b.text);

Make ES6 Thy Knight

Enhance readability by summoning the power of ES6 features like filter and concat.

let filteredArray = objectArray.concat(objectArray.filter(obj => !objectArray.some(existingObj => existingObj.name === obj.name))); // Object array merges its twin through a filter lane, now that's a fancy drive for uniqueness! πŸš—πŸ’¨

Nerd Corner: Performance Obsession

When performance is a calling card, the size and complexity of your array should be considered. The indexOf, find, and includes have diverse speed records that might affect performance, especially with larger arrays.

Code Cleanliness and Tricks

Avoid extending native objects like Array.prototype in shared environments. This can lead to surprise parties no one wants to attend!

Writing clear and maintainable code is your golden ticket to longevity in projects. Utility functions such as pushIfNotExist help create cleaner code, making it easy to test and read.