Stop treating extra attributes of an Array as elements (in Chrome)

I recently implemented a snippet that enhances Array's functionality by adding a getUnique function:

Array.prototype.getUnique = function() {
   var u = {}, a = [];
   for (var i = 0, l = this.length; i < l; ++i) {
      if (u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
};

One minor issue I encountered is that when I console.log an array, the attribute getUnique is displayed alongside the array elements:

["126", "125", getUnique: function]

This can be a bit distracting even though I understand that getUnique is not considered an array element. This behavior occurs in Chrome but not in Firefox. Is there a way to prevent this from happening?

Answer №1

To achieve a unique array in JavaScript, you can use the Object.defineProperty method along with enumerable:

Object.defineProperty(Array.prototype, 'getUnique',
{ enumerable: false
, configurable: true
, writable: true
, value: function ()
   {  var uniqueObj = {};
      var uniqueArr = [];
      for (var index = 0, len = this.length; index < len; ++index)
      {  if (uniqueObj.hasOwnProperty(this[index])) continue;
         uniqueArr.push(this[index]);
         uniqueObj[this[index]] = 1;
      }
      return uniqueArr;
   }
});

By default, properties are enumerable in JavaScript, making them visible through different iterations of the array like for-in loops or Object.keys. However, it's important to note that this method may not work on older browsers that do not support ES5.

Some developers advise against extending native constructors prototypes due to compatibility issues with older browser versions. An alternative approach is to define the function separately:

function getUniqueArray(arr)
{  var u = {};
   var a = [];
   for (var i = 0, l = arr.length; i < l; ++i)
   {  if (u.hasOwnProperty(arr[i])) continue;
      a.push(arr[i]);
      u[arr[i]] = 1;
   }
   return a;
}

It's worth mentioning that when using objects as keys in JavaScript, only one object will be printed by the getUnique function due to their string representation limitation. To overcome this, you may need to iterate through the array each time:

function getUnique(arg)
{
   var O = Object(arg);
   var len = O.length >>> 0;
   var A = [];
   var indexOf = function (arg, searchElement)
   {  for (var i = 0, l = arg.length; i < l; ++i) if (arg[i] === searchElement) return i;
      return -1;
   };
   for (var k = 0; k < len; ++k)
   {  var elementK = O[k];
      var kPresent = k in O;
      if (!kPresent || indexOf(A, elementK) !== -1) continue;
      A[A.length - 1] = elementK;
   }
   return A;
}

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

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: https://i.sstatic.net/irTju.png Below is the code snippet: import React, { useState, Fragment } from "react"; import S ...

Countdown alert using JavaScript

Currently in my frontend code, I am utilizing angularjs as the javascript framework. In a specific section of my code, I need to display an error message followed by a warning message in this format: If a user inputs an incorrect month, then the following ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

The mysterious disappearance of the div element exclusively in Chrome

Currently, I am working on an HTML/CSS chat application that is being integrated with the WebSocket API. However, I am facing an issue in Chrome only, as the div containing my input field and send button is not displaying on the page (this has been tested ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

Accessing URL parameters in VueJSIn Vue, retrieve

Based on the information provided in the documentation, I learned that I can extract parameters from the URL and pass them as a parameter to the component. To know more, refer to this link: https://router.vuejs.org/guide/essentials/passing-props.html#funct ...

Retrieve a collection containing all the variables that have been defined

I am attempting to gather all PHP defined variables and store them in an array. Previously, I tried: $myArr = get_defined_vars(); var_dump($myArr); The result was: array(4) { ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array ...

arranging data in a PHP array by column

I am attempting to organize the information in this data structure by a specific column. Here is how I have constructed it: $counter = 1; $entity_list = array(); foreach($result as $rec){ $entity_list[$counter]['student_first_name'] = $re ...

Tanstack onMutate Callback Fails to Activate Modal on React State Update

Currently, I am in the process of developing a Dapp and I need to incorporate transaction tracking. One issue I am facing is with trying to display a modal window when the approval setting process begins. Despite attempting to alter the isOpen state of the ...

What is the best way to resize an iframe containing a video to match the size of its parent

When using CSS, it is possible to stretch and adjust the ratio of an image to fully cover its parent div. The image will also resize accordingly if the parent div is responsive. Is this same effect achievable with videos (iframe) as well? EDIT: I am conce ...

Signs that indicate Angular has completed deferring

I'm having trouble grasping Angular's deferring and promises. I want to hide a "loading" message once all promises have been completed. Here's an example of my code: $scope.buildTeam = function () { $scope.Message = "loading..."; v ...

Stretch out single column content vertically in bootstrap for a uniform look

I've been struggling to make multiple buttons vertically stretch to fit the container, but I can't seem to remember how I achieved this in the past. I have experimented with various options outlined on https://getbootstrap.com/docs/4.0/utilities/ ...

Encoding the JSON output retrieved from an SQL database

Data Records: ID Domain Name 1 x.com 2 y.com 3 z.com $domainList = array(); $db_domains = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;"); foreach($db_domains as $row) { $domainList[] = $row->strDomain; } $output ...

Vue.js SyntaxError: Identifier came out of nowhere

An error was reported by VUE debug mode in this line of my code: :style="{transform : 'translate3d(' + translateX + 'px,0, 0)'}"\ The documentation does not provide instructions on how to include a variable within a style binding ...

Tips on organizing SAPUI5 OData prior to binding it to a control on the client side

Suppose I have an OData list represented in JSON format: var data = [ {"category" : "A", "value" : 1, "group" : "x"}, {"category" : "B", "value" : 2, "group" : "y"}, {"category" : "C", "value" : 3, "group" : "x"}, {"category" : "A", "value" : 4, "grou ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

What is the best method for changing the value of a DOM element depending on the status of another element?

Imagine implementing a text field that triggers the following code on each keydown event: if( $('#my_input').val() == '' ) $('#my_span').html('my input is blank'); else $('#my_span').html('My inpu ...