EJW EJW - 10 months ago 52
Javascript Question

Using hasOwnProperty() on an array

Can I use hasOwnProperty() on an array? I have this array of rgba values:

colors = [[240,120,120,255],[125,222,111,255],[9,56,237,255],[240,120,120,255],[240,120,120,255],[240,120,120,255]]

I'd like to create an object that sorts them in order of their frequency in the array. I'm trying a combination of things.

First I thought to convert the array into an object using:

function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i){
rv[i] = arr[i];
//console.log('the array is now this ', rv)
return rv;

But that returns something like this:


So i'm wondering if I can call hasOwnProperty on it like this?

function reduceColors(passedArray){
var empty = {}
return passedArray.filter(function(item){
return empty.hasOwnProperty(item["value"])

Answer Source

You can use hashing for this. With hashing you can group the arrays that have the same values in the same orders and you can count their frequency.

Here is an example:

var colors = [[240,120,120,255],[125,222,111,255],[9,56,237,255],[240,120,120,255],[240,120,120,255],[240,120,120,255]];

var hashed = [];

    var id = hash(arr);
    var contains = hashed.find(v => v.id == id);
        hashed.push({id:id, color:arr , count:1});

hashed.sort(function(a,b){return b.count - a.count;})


function hash(arr){
  var hash = "#";
  return hash;

In this example, I'm creating the hash by converting the rgba values to hexadecimal numbers, a better solution will be to store them like that (in hex) so you will have a one-dimensional array instead of a two-dimensional array.