0

How would you implement pythonic dictionary in Javascript that is able to store key value pairs and key can be tuple?

I'd like to find all anchors and then store values of it's href and title attributes to dictionary as keys (href value, title value) and number of occurrencies of this tuple as a value.

The code would look like this (it's a mix of Python and Javascript):

var anchors = document.querySelectorAll ("a");
d = []; // dictionary data structure
for (var i = 0, len = anchors.length; i < len; i++) {
  currentTuple = (anchors[i].href, anchors[i].title);
  if (!d.containsKey(currentTuple)) {
    d[currentTuple] = 1;
  } else {
   d[currentTuple] += 1;
  }
}

Maybe it would be easier if keys couldn't be tuples, but if it's possible i'd like to see it.

thank you

1
  • 1
    This library I've found quite useful for this purpose: timdown.co.uk/jshashtable. If you implement a custom .equals function, it should work for your needs. Commented Dec 17, 2011 at 13:01

1 Answer 1

1

Could this work? It just concatenates title and href as a unique key.

var data = [].reduce.call( document.links, function( data, a){
    var key = a.href+","+a.title;
    if( data[key] ) {
        data[key]++;
    }
    else {
        data[key] = 1;
    }   

return data;
}, {} );

http://jsfiddle.net/knYwb/

Sign up to request clarification or add additional context in comments.

17 Comments

You might need to use a different special character or excape commas in the title in order to guarantee uniqueness
@missingno, what do you mean? the comma isn't even necessary for that it's just for readability when you dump the object in console.
The problem is that when you concatenate you can theoretically have two separate tuples that generate the same key.
@missingno, yes and then you increment the occurrence of that key by one. It has same title+href combination as a one that already exists.
@xralf you would just loop through the data object and see which values are highest and then split their keys by , if you're using , as a separator.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.