We’ve got yet another “map” idea for you today, coming from the wooooorrrrlllllddd of Javascript clientside data structures, if you like.
We got onto this topic via reading https://www.w3schools.com/js/tryit.asp?filename=tryjs_map_groupby and https://medium.com/@sotoer/your-foreach-example-has-the-wrong-order-of-params-which-you-are-also-demonstrating-in-your-sample-42f5491b604e which both helped us enormously put together a rudimentary Fruit Inventory web application featuring …
- array with structure
// Create an Array
const fruits = [
{name:"apples", quantity:300},
{name:"bananas", quantity:500},
{name:"oranges", quantity:200},
{name:"kiwi", quantity:150}
];
- map object
var m = new Map();
- use of map.set() …
function addone() {
doadd=true;
fruits.push({name:"", quantity:0});
m.set('', 0);
doadd=false;
beadjustable();
}
… and Map.groupBy()
function thecall() {
// Group by ok and low
const result = Map.groupBy(fruits, myCallback);
// Display Results
let text ="These fruits are Ok: <br>";
try {
for (let x of result.get("ok")) {
if (x.name != '' || x.quantity != 0) {
text += x.name + " " + x.quantity + "<br>";
}
if (!m.has(x.name)) {
m.set(x.name, x.quantity);
}
}
} catch(ebad) { }
text += "<br>These fruits are low: <br>";
try {
for (let x of result.get("low")) {
if (x.name != '' || x.quantity != 0) {
text += x.name + " " + x.quantity + "<br>";
}
if (!m.has(x.name)) {
m.set(x.name, x.quantity);
}
}
} catch(ebad) { }
document.getElementById("demo").innerHTML = text;
console.log(result.get("ok"));
}
- contenteditable=true
function consolelog(inrec) {
if (rspan == 0) {
document.getElementById("tdname").innerHTML=inrec.split('value:')[1].split(' key:')[0].split(' map:')[0];
document.getElementById("tdquantity").innerHTML=inrec.split('key:')[1].split(' value:')[0].split(' map:')[0];
rspan=1;
} else if (inrec.split('value:')[1].split(' key:')[0].split(' map:')[0] == '') {
tabletds+='<tr><td contenteditable=true id=tdname' + rspan + ' onblur=fix(this);>' + inrec.split('value:')[1].split(' key:')[0].split(' map:')[0] + '</td><td contenteditable=true id=tdquantity' + rspan + ' onblur=fix(this);>' + inrec.split('key:')[1].split(' value:')[0].split(' map:')[0] + '</td></tr>';
rspan++;
} else {
tabletds+='<tr><td contenteditable=false id=tdname' + rspan + ' onblur=fix(this);>' + inrec.split('value:')[1].split(' key:')[0].split(' map:')[0] + '</td><td contenteditable=true id=tdquantity' + rspan + ' onblur=fix(this);>' + inrec.split('key:')[1].split(' value:')[0].split(' map:')[0] + '</td></tr>';
rspan++;
}
//alert(inrec);
if (doadd) {
fruits.push({name:"", quantity:0});
m.set('', 0);
tabletds+='<tr><td contenteditable=true id=tdname' + rspan + ' onblur=fix(this);></td><td contenteditable=true id=tdquantity' + rspan + ' onblur=fix(this);>0</td></tr>';
rspan++;
doadd=false;
}
}
- array.push()
… in map_test.html “proof of concept” Array and Map Tester web application …
If this was interesting you may be interested in this too.