EJW EJW - 2 months ago 8
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:

{0:[240,120,120,255],1:[125,222,111,255],2:[9,56,237,255],3:[240,120,120,255],4:[240,120,120,255],5:[240,120,120,255]}


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

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 = [];

colors.forEach(function(arr){
    var id = hash(arr);
    var contains = hashed.find(v => v.id == id);
    if(contains){
        contains.count++;
    }else{
        hashed.push({id:id, color:arr , count:1});
    }
});

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

console.log(hashed);

function hash(arr){
  var hash = "#";
  arr.forEach(function(v){
     hash+=v.toString(16);
  });
  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.