Smart Toggle of Array Elements in JavaScript: From Lodash to Native Set

Dec 08, 2025 · Programming · 8 views · 7.8

Keywords: JavaScript | Array Manipulation | ES6 Set

Abstract: This article explores various methods for intelligently toggling array elements in JavaScript (add if absent, remove if present). By comparing Lodash's _.union method, native ES6 Set data structure, and pure JavaScript implementations, it analyzes their respective advantages and disadvantages. Emphasis is placed on the benefits of prioritizing native JavaScript and Set in modern frontend development, including reduced dependencies, improved performance, and enhanced code maintainability. Practical applications in Angular.js environments and best practice recommendations are provided.

Introduction

In JavaScript development, there is often a need to intelligently manage array elements: adding a value when it does not exist in the array, and removing it when it does. This operation is particularly common in user interaction scenarios, such as toggling selection states or managing tag lists. This article explores solutions to this problem from multiple perspectives and analyzes the underlying technical principles.

Traditional Lodash Methods and Their Limitations

Lodash, as a popular JavaScript utility library, provides rich array manipulation methods. For smart toggling needs, the _.union function can be used:

_.union(scope.index, [val]);

This approach is concise but has significant limitations: _.union actually performs array merging and removes duplicates, but cannot achieve the "remove if present" logic. A more complete Lodash implementation requires combining multiple functions:

if (!_.includes(scope.index, val)) {
    scope.index.push(val);
} else {
    _.remove(scope.index, val);
}

While feasible, this introduces unnecessary dependencies and performs worse than native implementations.

The Revolutionary Improvement of ES6 Set Data Structure

The Set data structure introduced in ES6 perfectly fits the smart toggling requirement. Set is a collection of values where each value can occur only once, automatically handling duplicates.

var s = new Set();

// Adding values
s.add('hello');
s.add('world');
s.add('hello'); // Already exists, won't be added again

// Removing values
s.delete('world');

// Converting back to array
var array = Array.from(s);

The advantages of Set include: 1) automatic deduplication; 2) near O(1) time complexity for add and delete operations; 3) clear semantics directly expressing the "set" concept.

Pure JavaScript Implementation and Its Advantages

Without relying on external libraries, the same functionality can be achieved through pure JavaScript functions:

function toggleArrayElement(array, value) {
    var index = array.indexOf(value);
    if (index === -1) {
        array.push(value);
    } else {
        array.splice(index, 1);
    }
    return array;
}

This implementation offers the following advantages:

Practical Application in Angular.js Environment

In the Angular.js framework, smart toggling of array elements is often closely related to data binding and view updates. Here is an implementation example integrated with Angular.js:

angular.module('myApp', [])
.controller('MainCtrl', function($scope) {
    $scope.selectedItems = [];
    
    $scope.toggleSelection = function(item) {
        var index = $scope.selectedItems.indexOf(item);
        if (index === -1) {
            $scope.selectedItems.push(item);
        } else {
            $scope.selectedItems.splice(index, 1);
        }
    };
});

This approach fully utilizes Angular.js's data binding mechanism, ensuring synchronized updates between view and model.

Performance Comparison and Selection Recommendations

Benchmark tests reveal:

  1. For small arrays (<100 elements), performance differences among the three methods are minimal
  2. For medium arrays (100-10,000 elements), Set and pure JavaScript implementations significantly outperform Lodash
  3. For large arrays (>10,000 elements), Set performs best due to its hash table implementation providing near-constant operation time

Based on this analysis, the following recommendations are made:

  1. Prioritize ES6 Set, especially in scenarios requiring frequent add/remove operations
  2. Use pure JavaScript implementation if array format must be maintained
  3. Consider Lodash solutions only when the project is deeply dependent on Lodash and has no performance requirements

Extended Considerations and Best Practices

In actual development, the following factors should also be considered:

The trend in modern frontend development is to reduce external dependencies and fully utilize language-native features. This not only improves performance but also enhances code maintainability and team collaboration efficiency.

Conclusion

Smart toggling of JavaScript array elements is a common but important problem. The evolution from Lodash to native Set reflects the maturation of the JavaScript language itself and developers' pursuit of performance and maintainability. In actual projects, the most appropriate solution should be chosen based on specific requirements, but the overall trend is to prioritize language-native features and reduce unnecessary dependencies.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.