Enhance an Array directly through the prototype method

I have developed a custom method to clean up an array by removing duplicates and sorting it. It was successful and the code looked like this:

 // Example array.
var names = [ 'Lara', 'Lucy', 'Alexa', 'Vanessa', 'Lucy', 'Brianna', 'Sandra' ];

Array.prototype.clean_up = function(){
    var
        set = []
    ;
    this.forEach(function(item){
        if ( set.indexOf(item) === -1 ) {
            set.push(item);
        }
    });

    set.sort();

    return set;
};

My only issue is that I need to call it like this:

names = names.clean_up();

It would be more convenient if I could use it as Array.sort() for an in-place implementation. How can I achieve that?

names.clean_up();

EDIT: (Seems this belongs here and not in Answers)

The current solution I have implemented feels somewhat inefficient, and I am wondering if there is a better approach.

Array.prototype.clean_up = function(){
    var
        set = [],
        self = this
    ;
    this.forEach(function(item){
        if ( set.indexOf(item) === -1 ) {
            set.push(item);
        }
    });

    set.sort();

     // Reset and refill.
    while (this.length > 0) {
        this.pop();
    }

    set.forEach(function(item){
        self.push(item);
    });
};

It has been pointed out multiple times that modifying original arrays is not recommended. Why is that?

If a function like Array.sort() exists, indicating that the language is capable of such operations, why are custom functions discouraged? Why is sort() acceptable but a custom function is not?

Answer №1

If you are looking to modify the array directly, you need to identify and remove duplicates by using the splice method on the array. You can utilize Array.prototype.indexOf with a specified position to locate and eliminate duplicate elements.

Array.prototype.clean = function () {
  // Traverse through the array backwards
  this.reduceRight(function(acc, value, index, arr) {
    // Remove the element if its first occurrence is not at the current index
    if (arr.indexOf(value) != index) arr.splice(index, 1);
  }, null);
  // Sort the array
  this.sort();
  // Return the modified array for chaining
  return this;
}

var arr = 'aztatffgff'.split('');
console.log(arr.join());
console.log(arr.clean().join());

Iterating forwards over the array will not work as expected since splicing elements causes a shift in positions leading to skipping the next element. Directly creating a new array using functions like filter cannot be assigned back to the original array (this).

You could opt for a for loop instead of using reduceRight.

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

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

Determining in Angular whether a component tag includes a specific attribute

My usage of the app-somecomponent looks like this: <app-somecomponent required></app-somecomponent> I am trying to determine if the app-somecomponent element has the required attribute set in the app-somecomponent.component.ts file without sp ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

What could be causing my scene to fail to render?

I'm attempting to adapt this particular example into CoffeeScript. Below is a snippet of my code: class Example width: 640 height: 480 constructor: -> @camera = new THREE.PerspectiveCamera 45, @width/@height, 10000 @cam ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

The modal window pops up immediately upon the first click

Experience a dynamic modal element that springs to life with just the click of a button or an image. The magic lies in the combination of HTML, CSS, and jQuery code: <div id="modal-1" class="modal"> <div class="button modal-button" data-butto ...

Inject variables into the URL

Having access to an API that provides a list of images, I am presented with 5 parameters as listed below: The first parameter is the keyword for the search (e.g. flowers) The second parameter is size which has a default value The third parameter is orien ...

The bootpag event seems to trigger multiple times upon execution following an Ajax function call

I have integrated the bootpag jQuery pagination plugin from bootpag into my .NET/jQuery project. Within my project, there is a filtering menu that triggers an Ajax call to update the page with filtered or paginated data when a user selects a filtering opti ...

Unable to see the column filter in the data table

My datatable setup includes the column filter js on the page, everything is displaying and working smoothly without any errors in the console. However, after the smoothness loads, the inputs at the bottom are not visible. <body> <div id="stab ...

In the setup function, the composition API calculates the return value of the computed property before it is

I am currently working on editing a post using the state manager Vuex in Vue3 with Composition API. Below is the code I have implemented: <template> <div class="container py-5"> <h3 class="mb-5 border-top-0 border-start- ...

What is the best way to retrieve the value from a callback function in the outer scope?

I'm facing an issue with accessing values from a callback function in the parent scope. Essentially, I need to retrieve and use data fetched by the s3.getObject() function in the outer scope (last line). Below is my JavaScript code used for fetching ...

VueJS: A Closer Look at Parent-Child Communication

I have created two Vue components. The first one is called parent-component: Vue.component('parent-component',{ methods: { test: function(){ alert('Option Selected'); } }, te ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Testing asynchronous functions with Mocha

Currently, I am in the process of developing a node wrapper to interface with an external api. One particular challenge I am facing is testing the asynchronous functionality of the createJob method. Provided below is the test case code: api_key = "test_0d ...

Tips for effectively implementing React.usecallback

Looking for a way to rewrite the handleClick method using React.useCallback in a function called Parent, which is triggered by a button click event in React and TypeScript. function Parent () { const [isOpen, setIsOpen] = React.useState(false); ...

VueJS is utilized to duplicate the innerHTML output value

Currently diving into the world of Vue, I encountered an issue while rendering an HTML text. My component template is a WYSIWYG editor. <template> <div id='editor_container'> <slot name="header" /> <div id='editor ...

Can you explain the purpose of using the 'apply' method in this particular implementation of memoization in JavaScript?

_.memoize = function(func) { var cache = []; return function(n){ if(cache[n]){ return cache[n]; } cache[n] = func.apply(this,arguments); return cache[n]; } }; I'm curious about the usage of 'this' in func.appl ...

Unable to add an item from an array to the data property in Vue.js

When fetching data from Laravel, I use the following response: $unserialize = unserialize($import->field_names); return response()->json( $unserialize, 200 ) ; On Vue JS, I can view the response using: console.log(response); The data is displayed i ...