Saturday, August 20, 2016

Console magic

You can detect duplicate ids by evaluating this Javascript expresssion in Chrome devtools console:

    .map(function(ele){ return;})
    .reduce(function(countMap, word) {countMap[word] = ++countMap[word] || 1;return countMap}, {})

Boom! You will get:

> Object { 
   id1: 1, 
   id2: 1,
   some-other-id: 1,
   duplicate-id: 2

What is going on here:

  • document.querySelectorAll() returns the NodeList of elements that have id attribute
  • slice() - converts a NodeList to a JavaScript Array
  • map() - converts elements array to array of id strings
  • sort() - sorts the array. If you evaluate only up to here you will get the sorted list of ids (with duplicates)
  • reduce() - creates an object with id value as key and number of occurrences as value

Additionally, if you add Object.keys(resultFromAbove).sort() you will get a sorted list of unique ids.

Also an example of Map-Reduce 

BTW you can use similar, slightly modified selector expression to list the CSS classes that are used on the page and also mow many times.

No comments: