javascript adjacency matrix from object - javascript

I have problem with draw adjacency matrix from javascript object.
My object:
var result = {
"D5": ["D#5", "A#4", "D#5", "A#4"],
"D#5": ["D5", "D5"],
"A#4": ["G4", "D5", "F5"],
"G4": ["A#4"],
"F5": ["A#4"]
}
I want to get output:
D#5 A#4 D5 G4 F5
D5 2 2 0 0 0
D#5 0 0 2 0 0
A#4 0 0 1 1 1
G4 0 1 0 0 0
F5 0 1 0 0 0
How to count values in key?
I make draft:
for (var key in result){
console.log('Key: ' + key + ' values: ' + result[key])
for(var val in result[key]){
// console.log(result[key][val]);
var counter = 0;
for(var v in result[key]){
if (result[key][v] === result[key][val]){
counter++;
}
}
console.log('Value ' + result[key][val] + 'count' + counter)
}
}

You can use reduce
let result = {"D5":["D#5","A#4","D#5","A#4"],"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]};
let order = Object.keys(result).reduce((c,v)=>Object.assign(c,{[v]:0}),{}); //Make Dynamic Order
let count = Object.keys(result).reduce((c, v) => {
return Object.assign(c, {[v]: result[v].reduce((p, o)=>{
p[o] += 1;
return p;
}, Object.assign({}, order))});
}, {});
console.log(count);

This works, using forEach for result[key]
var result = {
"D5":["D#5","A#4","D#5","A#4"],
"D#5":["D5","D5"],
"A#4":["G4","D5","F5"],
"G4":["A#4"],"F5":["A#4"]
};
var final = {};
for (var x in result){
final[x] = {};
for(var y in result){
final[x][y]=0;
}
result[x].forEach(function(z){
final[x][z]++;
});
}
console.log(final);

You could use one Set to get all the unique sub-array elements, and then reduce method to get object with count of each element in those sub-array. Then you could add that data to one table.
const data = {"D5":["D#5","A#4","D#5","A#4"],
"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]}
const table = document.querySelector('table tbody');
const keys = new Set();
const output = Object.keys(data).reduce((r, key) => {
data[key].forEach(e => {
keys.add(e);
if (!r[key]) r[key] = {}
r[key][e] = (r[key][e] || 0) + 1;
})
return r;
}, {})
table.innerHTML += '<tr><td></td>' + Array.from(keys).map(e => `<td>${e}</td>`).join('') +'<tr>';
Object.keys(output).forEach(key => {
let data = `<td>${key}</td>`;
data += Array.from(keys, e => '<td>' + (output[key][e] ? output[key][e] : 0) + '</td>').join('')
table.innerHTML += `<tr>${data}</tr>`;
})
<table><tbody></tbody></table>

Just ES5
var result = {"D5":["D#5","A#4","D#5","A#4"],
"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]}
/***************************************************************************/
/*********************** THIS IS WHAT YOU ASKED ****************************/
/***************************************************************************/
function myCustomFunction(array){
// VAR USED TO STORE THE UNIQUE KEYS
var inner_keys = [];
// LOOP TO GET THE UNIQUE KEYS
Object.keys(array).map(function(a){inner_keys = inner_keys.concat(array[a])})
inner_keys = inner_keys.filter(function(a,b,c){return c.indexOf(a) === b});
// VAR USED TO STORE THE FINAL RESULT
var result = {};
// LOOP TO GET THE AMOUNT OF REPETITION FOR EACH KEY IN THE ORIGINAL ARRAY
Object.keys(array).map(function(a){
result[a] = inner_keys.map(function(b){return array[a].filter(function(c){return c==b}).length})
})
// RETURNS THE UNIQUE KEYS AND THE RESULT
return {orderOfKeys: inner_keys, result: result};
}
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
/******************** THIS IS JUST TO PRINT IT INTO A TABLE ***************/
/**************************************************************************/
function fillTable(array){
var table_header = array.orderOfKeys;
var table_body = array.result;
var thead = document.getElementById("thead");
var tbody = document.getElementById("tbody");
createElement('TR', thead)
for(var i = 0; i < table_header.length; i++){
if(i == 0){
createElement('TH', thead.children[0], '')
}
createElement('TH', thead.children[0], table_header[i])
}
for(var k in table_body){
var row = createElement('TR', tbody);
for(var i = 0; i < table_body[k].length; i++){
if(i == 0){
createElement('TD', row, k)
}
createElement('TD', row, table_body[k][i])
}
}
}
function createElement(el, parent, value){
var element = document.createElement(el);
if(value != undefined){
var element_text = document.createTextNode(value);
element.appendChild(element_text);
}
parent.appendChild(element);
return element;
}
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
fillTable(myCustomFunction(result))
<table>
<thead id="thead">
</thead>
<tbody id="tbody">
</tbody>
</table>

Related

Javascript , sum of key pair value's

anyone have a solution to add up these key pair values for the one key? I've tried to add them to the key pair value using dict[id] += parseFloat(value) but it results in incorrect operation. I've tried using eval(valuestring), I'm pretty sure the value's inside the key are still a string. Need to get the sum of each ID for a leaderboard.
Any help is much appreciated.
Output of keys of dict_tips
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,' ]
Core
var dict_tips = [];
var dict_counts = [];
var sum = []
for (var i = 0; i < 200 ; i++) {
var str = res.messages.matches[i].text;
var stdout = capcon.captureStdout(function scope() {
for (var x = 46 ; x < 55 ; x++) {
process.stdout.write(str[x]);
}
});
var id = JSON.stringify(stdout.match(/.{1,9}/g))
var stdout = capcon.captureStdout(function scope() {
for (var x = 76 ; x < 85 ; x++) {
process.stdout.write(str[x]);
} });
var extract = JSON.stringify(stdout.match(/.{1,9}/g));
var parse = extract.indexOf(/.RDD|RD|R|D|:| /g)
var x = checkAndAdd(id,extract)
function checkAndAdd(id,extract) {
var found = dict_tips.some(function (el) {
return el.key === id; })
if (!found) { if (parse = -1)
{
var format = ( ""+extract.slice(2,9)).replace(/.RDD|RD|R|D|:| /g,'');
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips.push({key: id})
dict_tips[id] += total
}
else
{
var format = extract.slice(2,9)
var x = format.substr(0, 9) + " " + format.substr(9)
var total = x.split(" ")
dict_tips.push({key: id})
dict_tips[id] = "";
dict_tips[id] += total
}
}
else
{
var extract = stdout.match(/.{1,9}/g);
var parse = extract.indexOf(/.RDD|RD|R|D|:| /g)
if (parse = -1)
{
var format = ( "" + extract).replace(/.RDD|RD|R|D|:| /g,'');
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips[id] += total
}
else
{
var format = extract.slice(1,9)
var x = format.substr(0, 9) + " " + format.substr(9);
var total = x.split(" ")
dict_tips[id] += total
};
}
}
}
var sum = dict_tips.reduce(function(a, b) { return a + b; }, 0);
console.log(JSON.stringify(sum))
console.log(dict_tips)
Split the string, then parseFloat and sum up the values:
const data = {
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,'
}
const sums = Object.keys(data).reduce((results, key) => {
results[key] = data[key].split(',')
.map(item => parseFloat(item))
.filter(item => !isNaN(item))
.reduce((res, item) => res + item, 0)
return results
}, {})
console.log(sums)
In PHP, you would do an explode on the commas, think for javascript its split. After you would run a loop through each index of the array that the split function just created and adding to a total sum. You would need to do a parsefloat on each value of the index as well.
You can simply iterate through the keys of the data using for in.
Then you need to split the string into an array, and sum up the values using reduce.
const data = {
'["U5WUV3A3G"]': '1000.0,200.0,300.0,100.0,500.0,420.0,42.0,98.0,500.0,150.0,300.0,300.0,25.0,200.0,',
'["U5FHMCWP7"]': '50.0,500.0,1000.0,45.0,1000.0,100.0,15.0,3.0,675.0,100.0,225.0,25.0,900.0,100.0,1000.0,10.0,30.0,0.001,0.005,1.755,1.724,1.5,',
'["U5SJQMME3"]': '100000.,100.0,100.0,100.0,50.0,100.0,100.0,40000.0,10.0,200.0,500.0,',
'["U6KAYAJ5Q"]': '100.0,200.0,900.0,100.0,100.0,100.0,1000.0,10.0,10.0,1000.0,100.0,100.0,1.0,10.0,800.0,200.0,100.0,190.0,190.0,10.0,10.0,',
'["U6F1AHQ8H"]': '10.0,100.0,',
'["U3H65TS9K"]': '500.0,100.0,200.0,500.0,35.414,12.345,',
'["U5HUZG3MF"]': '1.0,0.5,42.0,44.0,1.0,1.0,7.995,100.0,100.0,100.0,50.0,100.0,4.0,5.0,5.0,5.0,5.0,5.0,',
'["U5ZPTLXV5"]': '5.0,',
'["U6EMQC2LF"]': '737.998,2000.0,1000.0,300.0,666.0,6000.0,5000.0,5000.0,1000.0,5000.0,999.0,1.0,5000.0,3000.0,5000.0,9999.0,',
'["U62EVB2P7"]': '50.0,20.0,100.0,1.0,100.0,50.0,100.0,50.0,100.0,100.0,1.0,',
'["U3GJ9SREZ"]': '150.0,100.0,100.0,100.0,',
'["U6F0KBT2P"]': '1000.0,100.0,1000.0,100.0,800.0,100.0,100.0,',
'["U5WD17D5E"]': '150.0,75.0,',
'["U697Y6BL3"]': '5.0,1.0,51.0,2.0,1.0,1.0,5.0,',
'["U6GU038HX"]': '4000.0,',
'["U4B0NK2NR"]': '100.0,500.0,200.0,100.0,100.0,100.0,100.0,',
'["U6C23F8MT"]': '49.0,100.0,',
'["U5KQY01ST"]': '105.0,',
'["U6FSC0CC8"]': '100.0,100.0,',
'["U659939GF"]': '20.0,100.0,100.0,100.0,',
'["U5URNPRSA"]': '5.0,20.0,5.0,5.0,50.0,',
'["U5VAMV76F"]': '0.5,20.0,200.0,200.0,200.0,200.0,100.0,200.0,5.0,500.0,200.0,50.0,',
'["U5UL7KWKU"]': '150.0,200.0,',
'["U61NYHM25"]': '64.0,2.0,',
'["U6CMX965S"]': '10.0,10.0,20.0,50.0,30.0,',
'["U5G40R5PF"]': '499.0,',
'["U4XHS3DHA"]': '51.0,',
'["U69MY9WDS"]': '10.0,6.414,10.0,10.0,',
'["U666S65RC"]': '100.0,100.0,',
'["U5X3MEZ39"]': '1.0,1.0,10.01,10.1,0.002,0.01,1.1,'
}
let sum = {};
for (var key in data) {
let arr = data[key].split(',');
let total = arr.reduce((acc, curr) => {
if (parseInt(curr)) {
return acc + parseInt(curr);
}
return acc;
}, 0);
sum[key] = total;
}
console.log(sum)

Create Array of Objects and count number of occurrence

I have an array of objects and want to create another array of objects based on.
I want to check if an object is repeated just want to show the count, otherwise show the object itself with count = 1.
<!-- I have an array-->
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
// I want to create another array based on "arr" like the one below
var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
//Any hint please
This may help you. This answer considers name or some identifier will be unique for each object.
counter = {}
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
var obj = {};
var counter = {}
for (var i = 0, len = arr.length; i < len; i++) {
obj[arr[i]['name']] = arr[i];
counter[arr[i]['name']] = (counter[arr[i]['name']] || 0) + 1
}
newArr = new Array();
for (var key in obj){
newArr.push(extend( obj[key], {count:counter[key]}));
}
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
console.log(newArr)
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var countNameMapping = {}, finalArr = [];
var arrLength = arr.length;
for(i=0; i<arrLength; i++){
var tempObj = {name:arr[i], price:arr[i].price, occurance:1};
var productName = arr[i].name;
if(countNameMapping[productName] === undefined){
countNameMapping[productName] = tempObj;
}else{
countNameMapping[productName].occurance += 1;
}
}
for(var k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr );
You can try this one:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var result = [];
arr.map(function(arrObject) {
if (result.length > 0) {
result.map(function(resultObject) {
if (resultObject.name != arrObject.name) {
arrObject.count = 1;
result.push(arrObject);
} else {
resultObject.count++;
}
})
} else {
arrObject.count = 1;
result.push(arrObject);
}
})
console.log(result);
This will provide the result you are looking for:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var map = arr.reduce((accum, item) => {
var obj = accum.get(item.name) || Object.assign({}, item, {count:0});
obj.count++;
return accum.set(item.name, obj);
}, new Map());
var res = [...map.values()];
More or less...
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
// I want to create another array based on "arr" like the one below
// var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
var count = {};
var test = [];
for (var i = 0, len = arr.length; i < len; i++) {
var id = JSON.stringify(arr[i]);
if (count.hasOwnProperty(id)) {
count[id].count++;
} else {
test.push(arr[i]); // Data contamination. Too lazy to copy object
count[id] = test[test.length - 1]; // Could be better.
count[id].count = 1;
}
}
console.log(test);
This is probably what are you looking for:
How does it work?
First, your array arr will use a forEach loop to find each object and if if new you will add it to the results array. The method isNew() will return true if the object is new.
For each new object founded you will count the number of occurrences using findOccurrences() To reduce the number of "loops" you will slice the array according to the index. So you don't need to search again over the already processed data.
So now you can build an new object, using the name, price and count.
Finally, you can push() the new object to the results array.
var arr =[{name:"coke",price:20},{price:20,name:"coke"},{name:"coke",price:20},{name:"kabab",price:250}];
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
arr.forEach(function(obj) {
if (isNew(obj)) {
var counter = findOccurrences(obj, arr.slice(index, arr.length));
var newObj = {
name: obj.name,
price: obj.price,
count: counter
}
results.push(newObj);
}
index++;
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function isNew(newObj) {
var wasFound = true;
if (typeof results != "undefined" && results != null && results.length > 0) {
results.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
return false;
} else {
wasFound = false;
}
});
return !wasFound;
} else {
return true;
}
}
function findOccurrences(newObj, objects) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
count++;
}
});
}
return count;
}
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original"><p>Original Array</p></div>
<div id="results"><p>Results Array</p></div>
Update:
More optimization.
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var accumulator = {};
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
var c = (hash & 0x0FFFFFFF)
.toString(16)
.toUpperCase();
return '0000000'.substring(0, 7 - c.length) + c;
};
arr.forEach(function(obj) {
var id = JSON.stringify(obj).hashCode();
console.log(id);
if (accumulator.hasOwnProperty(id)) {
accumulator[id].count++;
} else {
results.push(obj);
accumulator[id] = results[results.length - 1];
accumulator[id].count = 1;
}
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original">
<p>Original Array</p>
</div>
<div id="results">
<p>Results Array</p>
</div>

How to get property of dynamic table

I have some trouble with my project,
I need to build a game : Mine Sweeper,
My main problem in this project is that I have dynamic table in my html page
that I build that matrix in my Javascript page,
I want to get the current cell I pushed it by onclick event and I only got the first cell (0,0):
It's my home work project , I only need help to understand how can I get the index of each cell I`ve been clicked on ,
my html page :
<body onload="initGame()">
<header>
<h1>My Mine Sweeper</h1>
</header>
<table class="mineTable" onclick="cellClicked(this)" border="1">
<tbody class="mineSweeperTable" ></tbody>
</table>
my javascript Page :
'use strict';
var gMINE = '❉';
var gCELL = ' ';
var gLevel = {
SIZE : 4 ,
MINES: 0.2
};
var gCell ={
i : 0 ,
j : 1
}
var gMineSweeper = [];
function getRandomCell() {
return (Math.random() > gLevel.MINES)? gCELL : gMINE ;
}
function initGame() {
buildBoard();
renderBoard(gMineSweeper);
countMines(gMineSweeper);
//setMinesNeighborsCount(gMineSweeper);
}
function buildBoard() {
var elCell = document.querySelectorAll ('td');
for (var i = 0; i < gLevel.SIZE; i++) {
gMineSweeper.push([]);
for (var j = 0; j < gLevel.SIZE; j++) {
gMineSweeper[i][j] = getRandomCell();
}
}
}
function renderBoard(board) {
var elMineSweeperTable = document.querySelector('.mineSweeperTable');
var strHTML = '';
board.forEach(function (row) {
strHTML += '<tr>';
row.forEach(function (cell) {
strHTML += '<td> ' + cell + ' </td>'
});
strHTML += '</tr>'
})
elMineSweeperTable.innerHTML = strHTML;
}
function countMines(board) {
var count = 0;
board.forEach(function(row) {
row.forEach(function(cell) {
if(cell === gMINE){
count++;
}
});
});
console.log('Mines Count : ' , count);
return count;
}
function cellClicked(elCell,i,j) {
var elCell = document.querySelectorAll ('td');
console.log('You Clicked on me ! : ' , elCell,i,j);
debugger;
}
function setMinesNeighborsCount(board) {
var elCell = document.querySelector('td');
// debugger;
// for (var i = 0; i < board; i++) {
// gMineSweeper.push([]);
// for (var j = 0; j < board; j++) {
// var ngbrsCount = countNgbrs(i, j);
// console.log('Cell ', i, ', ', j, ' has: ', ngbrsCount );
// if (ngbrsCount > 0) {
// debugger;
// board.push(ngbrsCount);
// // elCell.innerHTML = ngbrsCount;
// cell[i][j] = ngbrsCount;
// elCell = cell[i][j];
// }
// // debugger;
// if (cell === gMINE) {
// console.log('This cell is Mine', i, j);
// // debugger;
// // board.push(ngbrsCount);
// }
// }
// }
var c = elCell;
debugger;
board.forEach(function (row, i) {
row.forEach(function (cell, j) {
var ngbrsCount = countNgbrs(i, j);
console.log('Cell ', i, ', ', j, ' has: ', ngbrsCount );
if (ngbrsCount > 0) {
//board.push(ngbrsCount);
// elCell.innerHTML = ngbrsCount;
//debugger;
c[i][j] = ngbrsCount;
}
debugger;
if (cell === gMINE) {
console.log('This cell is Mine', i, j);
//debugger;
// board.push(ngbrsCount);
}
});
});
}
function countNgbrs(i, j) {
var count = 0;
for (var a = i-1; a <= i+1; a++){
if ( a < 0 || a >= gMineSweeper.length ) continue;
for (var b = j-1; b <= j+1; b++){
if ( b < 0 || b >= gMineSweeper.length ) continue;
if ( a === i && b === j ) continue;
if (gMineSweeper[a][b] === gMINE) count++;
}
}
return count;
}
To get the postion of the from table tag using jQuery
HTML
<td onclick='Getposition($(this))'></td>
function Getposition(e){
var col = e.index() + 1;
var row = e.closest('tr').index() + 1;
alert( [col,row].join(',') );
}
Example Fiddle
http://jsbin.com/lupifilike/2/edit?html,js,output
function cellClicked(el) {
document.querySelector('.mineTable').onclick = function(){
var el = event.target;
console.log('td clicked' , el);
debugger;
if(el.innerText === gMINE){
console.log('Game Over! ');
}
};
}
its working that way :)

How to get the repeated letter in a string?

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";
Here I want to get the maximum and minimum entered values.For example, I have entered letter "a" as 10 times. That was the maximum. So I want to pint that value. How can I get the maximum entered values in a String using jquery or javascript.
A proposal with Array#forEach() and an object count:
var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh",
count = {}, min, max;
a.split('').forEach(function (a) {
count[a] = (count[a] || 0) + 1;
});
Object.keys(count).forEach(function (a, i) {
if (!i) {
min = [a];
max = [a];
return;
}
if (count[a] < count[min[0]]) {
min = [a];
return;
}
if (count[a] > count[max[0]]) {
max = [a];
return;
}
if (count[min[0]] === count[a]) {
min.push(a);
}
if (count[max[0]] === count[a]) {
max.push(a);
}
});
document.write('min: ' + min.join(', ') + ' with occurrence of ' + count[min[0]] + '<br>');
document.write('max: ' + max.join(', ') + ' with occurrence of ' + count[max[0]] + '<br>');
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');
How can I get the maximum entered values in a String using jquery or
javascript.
try this
var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";
var allchars = a.split("").sort();
var output = {};
allchars.forEach(function(val){ output[val] = output[val] || 0; output[val]++; });
Now find the key with highest value
var highestProp = "";
var highestValue = 0;
var lowestProp = "";
var lowestValue = Number.MAX_SAFE_INTEGER;
Object.keys(output).forEach(function(key){
if (output[key] > highestValue )
{
highestValue = output[key];
highestProp = key;
}
if (output[key] < lowestValue )
{
lowestValue = output[key];
lowestProp = key;
}
});
Now highestValue and highestProp has the highest values and highest-value property name. Similarly lowestValue and lowestProp has the lowest values and lowest-value property name.
DEMO
var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";
var allchars = a.split("").sort();
var output = {};
allchars.forEach(function(val){ output[val] = output[val] || 0; output[val]++; });
var highestProp = "";
var highestValue = 0;
var lowestProp = "";
var lowestValue = Number.MAX_SAFE_INTEGER;
Object.keys(output).forEach(function(key){
if (output[key] > highestValue )
{
highestValue = output[key];
highestProp = key;
}
if (output[key] < lowestValue )
{
lowestValue = output[key];
lowestProp = key;
}
});
alert(highestProp + " has the highest frequency of " + highestValue);
alert(lowestProp + " has the lowest frequency of " + lowestValue);

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Categories

Resources