Javascript , sum of key pair value's - javascript

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)

Related

isset equivalent in javascript to find palindrome

I created a script in PHP to find a palindrome, but when I try to do the same in JavaScript, then it is not working as expected. It's not just a matter of checking if the string that is reversed matches, but any order of the string has to be checked as well.
In other words, "mom" should return as true, "mmo" should return as true, "omm" should return as true, etc..., which is what the PHP script does, but the JS script below doesn't even work for the first iteration for the string "mom"
The following is the PHP script:
<?php
function is_palindrom($str) {
$str_array = str_split($str);
$count = array();
foreach ($str_array as $key) {
if(isset($count[$key])) {
$count[$key]++;
} else {
$count[$key] = 1;
}
}
$odd_counter = 0;
foreach ($count as $key => $val) {
if(($val % 2) == 1) {
$odd_counter++;
}
}
return $odd_counter <= 1;
}
echo is_palindrom('mom') ? "true" : "false";
The following is what I have tried in JS:
var count = [];
var strArr = [];
var oddCounter = 0;
var foreach_1 = function(item, index) {
console.log("count[index]: " + count[index]);
if (typeof count[index] !== "undefined") {
count[index]++;
} else {
count[index] = 1;
}
};
var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
if (eval(item % 2) == 1) {
oddCounter++;
}
console.log("oddCounter: " + oddCounter);
return oddCounter <= 1;
};
var isPalindrom = function(str) {
strArr = str.split("");
console.log(strArr);
strArr.forEach(foreach_1);
console.log(count);
count.forEach(foreach_2);
};
I believe it is failing where I try to replicate isset in javascript, with the following code:
if (typeof count[index] !== "undefined") {
As a result, I have tried to write my own isset function, but still the same result, it is not working:
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
With the following function being called:
if (isset(count[index])) {
count[index]++;
} else {
count[index] = 1;
}
As usual, any help would be appreciated and thanks in advance
BTW, it's killing me that I cannot remember the word for several revisions or iterations of something - I know that it starts with "re"
My attempt:
let p1 = `No 'x' in Nixon.`
let p2 = `Was it a car or a cat I saw?`
let p3 = `A man, a plan, a canal, Panama!`
function is_palindrome (str) {
const normalize = str => str.replace(/[.,:;`'"!?\/#$%\^&\*{}=\-_~()\s]/g, '').toLowerCase()
const reverse = str => [...str].reverse().join('')
return normalize(str) === reverse(normalize(str))
? true
: false
}
console.log(is_palindrome(p1))
console.log(is_palindrome(p2))
console.log(is_palindrome(p3))
First, thank you for all the comments.
Second, I ran a var_dump on the count array in the PHP file and this was the result:
array (size=2)
'm' => int 2
'o' => int 1
Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.
One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:
var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";
var mForN = function(obj, strArr) {
for (var y = 0; y < strArr.length; y++) {
// console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
if (isset(obj[strArr[y]])) {
obj[strArr[y]]++;
} else {
obj[strArr[y]] = 1;
}
}
return obj;
};
var mForN_2 = function(obj, objKeys) {
for (var z = 0; z < objKeys.length; z++) {
/* console.log(
"obj[objKeys[z]]: " +
obj[objKeys[z]] +
" obj[objKeys[z]] % 2: " +
eval(obj[objKeys[z]] % 2)
); */
if (eval(obj[objKeys[z]] % 2) == 1) {
oddCounter++;
}
// console.log("oddCounter: " + oddCounter);
}
return oddCounter <= 1;
};
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
var isPalindrom = function(str) {
// reverse original string
splitString = str.split("");
reverseArray = splitString.reverse();
joinArray = reverseArray.join("");
var checking = checkSpellingOfStr(str);
if (str == joinArray) {
strArr = str.split("");
// console.log("strArr: " + strArr);
objKeys = makeObjKeys(count, strArr);
// console.log("filled count before mForN: " + JSON.stringify(count));
// create array of keys in the count object
objKeys = Object.keys(count);
// console.log("objKeys: " + objKeys);
count = mForN(count, strArr);
// console.log("count after mForN: " + JSON.stringify(count));
return mForN_2(count, objKeys);
} else {
return 0;
}
};
var makeObjKeys = function(obj, arr) {
for (var x = 0; x < arr.length; x++) {
obj[arr[x]] = null;
}
return obj;
};
var checkSpellingOfStr = function(someStr) {
var formData = {
someWord: someStr
};
$.ajax({
type: "GET",
url: url,
data: formData,
success: function(result) {
if (!$.trim(result)) {
} else {
console.log(result);
$("#checkSpelling").html(result);
}
}
});
};
Start everything with the following call:
isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
In my example, I have a form and I listen for a button click as follows:
var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});
The following is the php for spell check:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!empty($_REQUEST['someWord']))
{
$someWord = $_REQUEST['someWord'];
}
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, $someWord)) {
echo trim($someWord) . " is a recognized word in the English language";
} else {
echo "Your word is either misspelled or that is not a recognized word";
}
You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini
This is what I did, to get it running locally on my mac:
cd /Users/username/Downloads/php-5.6.2/ext/pspell
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
make
cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
sudo apachectl restart
check your phpinfo file and you should see the following:
pspell
PSpell Support enabled
Live example

javascript adjacency matrix from object

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>

How to combine result of two test in javascript

I have a javacsript function, her result 2 arrays, one contains the 10 top turnover of customers and the other contains the 10 bottom turnover of customers.
I did my Graph and I fill it by the two arrays.
I want add a scatter type triangle with a green color above each chart that contains a positive turnover and bellow each chart that contains a negative turnover and red color.
I found this solution.
var query1 = {{repair_semestre1}};
var query2 = {{repair_semestre2}};
function formatName(o) {
return "Client: " + o.client + ", LRU.: " + o.article + ", semester t/o: " + o.turnovers + " " + o.percent;
}
var data = {};
var output = [];
var max = [];
var min = [];
var client;
var article;
[query1, query2].forEach(function (query, semester) {
query.Client.forEach(function (clientId, index) {
var client = data[clientId] = data[clientId] || {};
var clientArt = client[query.LRU[index]] = client[query.LRU[index]] || [0, 0];
clientArt[semester] = query.round[index];
});
});
for (client in data) {
for (article in data[client]) {
var turnovers = data[client][article];
if (turnovers[0]!=0) {
output.push({ client, article, turnovers,
percent: turnovers[0] === 0 ? turnovers[1] :
((turnovers[1] - turnovers[0]) / turnovers[0]) *100 });
}
}
}
output.sort(function (a, b) {
return b.percent - a.percent;
});
var target = output.slice(0,10);
var clients = [];
var lrus = [];
var percents = [];
for (var i = 0; i < target.length; i++) {
clients.push(target[i].client);
lrus.push(target[i].article);
percents.push(target[i].percent);
}
var target2 = output.slice(-10);
var clients2 = [];
var lrus2 = [];
var percents2 = [];
for (var i = 0; i < target2.length; i++) {
clients2.push(target2[i].client);
lrus2.push(target2[i].article);
percents2.push(target2[i].percent);
}
target={client: clients, lru: lrus, percent: percents};
target2={client: clients2, lru: lrus2, percent: percents2};
return {
target:target,
target2:target2
}
I should do another function to test the value of each turnover. I did this function shown below, but always it return just the result of the first test.
var target1={{calcul_turnover.target.percent}}
var target2 ={{calcul_turnover.target2.percent}}
for(var i =0; i < target1.length; i++){
if(target1[i] < 0){
return 0
}else
return 1
}
for(var i =0; i < target2.length; i++){
if(target2[i] < 0){
return 0
}else
return 1
}
How can I combine the results of the two tests?
Thank you

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 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);

Categories

Resources