JavaScript: Remove duplicates of objects sharing same property value

This function removes duplicate values from an array by returning a new one. function removeDuplicatesBy(keyFn, array) { var mySet = new Set(); return array.filter(function(x) { var key = keyFn(x), isNew = !mySet.has(key); if (isNew) mySet.add(key); return isNew; }); } var values = [{color: “red”}, {color: “blue”}, {color: “red”, number: 2}]; var withoutDuplicates = removeDuplicatesBy(x => … Read more

Java – How to create new Entry (key, value)

There’s public static class AbstractMap.SimpleEntry<K,V>. Don’t let the Abstract part of the name mislead you: it is in fact NOT an abstract class (but its top-level AbstractMap is). The fact that it’s a static nested class means that you DON’T need an enclosing AbstractMap instance to instantiate it, so something like this compiles fine: Map.Entry<String,Integer> … Read more

Swap key with value in object

function swap(json){ var ret = {}; for(var key in json){ ret[json[key]] = key; } return ret; } Example here FIDDLE don’t forget to turn on your console to see the results. ES6 versions: static objectFlip(obj) { const ret = {}; Object.keys(obj).forEach(key => { ret[obj[key]] = key; }); return ret; } Or using Array.reduce() & Object.keys() … Read more

Can’t access cookies from document.cookie in JS, but browser shows cookies exist

You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions. So you either have to disable the httponly flag or you need to find another … Read more