Using hasOwnProperty() on an array

EJW picture EJW · Oct 3, 2016 · Viewed 13.4k times · Source

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

Titus picture Titus · Oct 3, 2016

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, 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.