Using hasOwnProperty() on an array

Tags: , ,

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"])


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 => == 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, but a better solution will be to store them like that (in hexadecimal), so you will have a one-dimensional array instead of a two-dimensional array.

Source: stackoverflow