Get the largest value from Json object with Javascript - javascript

This should be an easy one. I just cant figure it out.
How do I get the largest value from this piece of JSON with javascript.
{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}
The key and value I need is:
"two":35
as it is the highest
thanks

var jsonText = '{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}'
var data = JSON.parse(jsonText).data
var maxProp = null
var maxValue = -1
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var value = data[prop]
if (value > maxValue) {
maxProp = prop
maxValue = value
}
}
}

If you have underscore:
var max_key = _.invert(data)[_.max(data)];
How this works:
var data = {one:21, two:35, three:24, four:2, five:18};
var inverted = _.invert(data); // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'};
var max = _.max(data); // 35
var max_key = inverted[max]; // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'}[35] => 'two'

This is my function for biggest key
function maxKey(a) {
var max, k; // don't set max=0, because keys may have values < 0
for (var key in a) { if (a.hasOwnProperty(key)) { max = parseInt(key); break; }} //get any key
for (var key in a) { if (a.hasOwnProperty(key)) { if((k = parseInt(key)) > max) max = k; }}
return max;
}

You can also iterate the object after you parse JSON .
var arr = jQuery.parseJSON('{"one":21,"two":35,"three":24,"four":2,"five":18}' );
var maxValue = 0;
for (key in arr)
{
if (arr[key] > maxValue)
{
maxValue = arr[key];
}
}
console.log(maxValue);

Related

Is there way to pass values dynamically through array instead of using indexes

[image][1] [1]: https://i.stack.imgur.com/W7bNt.png
Right now it works like this:
1- when key's index 0 do this,
2- when key's index 1 do this,
3- when key's index 2 do this.
but I want to add min and max value for objectVal array that can fix (for stance key[min], n , key[max]) but nth values in between, like it can add new keys and values in slider dynamically instead of calling its indexs and adding new conditional operators.
const sliders = document.querySelectorAll(".allSliders");
let result = document.querySelector(".result");
let totalNumber = 0;
let values = [];
let sliderNums = [];
let objectVal = [
{
keys: [0, 500,1000],
values: [0.0045, 0.0044,0.0043]
},
{
keys: [0, 500,1000],
values: [0.0045, 0.0044,0.0043]
},
{
keys: [0, 500,1000],
values: [0.0045, 0.0044,0.0043]
},
];
sliders.forEach((sliderNumber, id) => {
sliderNumber.addEventListener("input", () => {
let action =
objectVal[id].keys[3] - objectVal[id].keys[3];
let maxLine = objectVal[id].keys[3] + action;
let getInformation = maxLine - action * 0.666;
sliderNumber.setAttribute("max", maxLine);
let currentRange = parseInt(sliderNumber.value);
sliderNums[id] = currentRange;
function line(value, currentVal, obj)
{
values[id] = currentVal * obj;
sliderNumber.nextElementSibling.querySelector(
".tooltiptext"
).textContent = `(${currentVal} * ${obj})`;
sliderNumber.nextElementSibling.querySelector(".dollar").textContent =
values[id].toFixed(2);
}
if (
currentRange > objectVal[id].keys[0] &&
currentRange <= objectVal[id].keys[3] )
{
line(values[id], currentRange, objectVal[id].values[0])
}
else if (
currentRange > objectVal[id].keys[3] &&
currentRange <= objectVal[id].keys[3]
) {
line(values[id], currentRange, objectVal[id].values[3])
}
else {
line(values[id], currentRange, objectVal[id].values[3])
}```

im unable to remove adjacent vaules from array

im trying to remove adjacent duplicates but instead of desired result (3 results) i'm getting only 2 results
my Expected Output:
[{"mw://HOME_BIN":{"position":0}},{"mw://diagnosis_HOME":{"position":3}},{"mw://HOME_BIN":{"position":3}}]
here is what i have tried:
var arr = [{"mw://HOME_BIN":{"position":0}},{"mw://diagnosis_HOME":{"position":3}},{"mw://HOME_BIN":{"position":3}},{"mw://HOME_BIN":{"position":3}}];
var nArr = [];
for(var i = 0; i < arr.length;++i){
var key1 = Object.keys(arr[i]).join('');
var nLength = ((i + 1) > arr.length - 1 ) ? 0 : i + 1;
var key2 = Object.keys(arr[nLength]).join('');
if(key1 == key2) continue;
nArr.push(arr[i]);
}
console.log(nArr);
from the above result you can see one more element is missing
Easier to use filter:
var arr = [{"mw://HOME_BIN":{"position":0}},{"mw://diagnosis_HOME":{"position":3}},{"mw://HOME_BIN":{"position":3}},{"mw://HOME_BIN":{"position":3}}];
let lastKey;
const filtered = arr.filter((item) => {
const key = Object.keys(item)[0];
if (key === lastKey) return false;
lastKey = key;
return true;
});
console.log(filtered);
If you're looking for adjacent keys, you should just track the latest key, and not compare all of them.
var arr = [{"mw://HOME_BIN":{"position":0}},{"mw://diagnosis_HOME":{"position":3}},{"mw://HOME_BIN":{"position":3}},{"mw://HOME_BIN":{"position":3}}];
let result = [], prev_key = '', key;
for(let item of arr) {
key = Object.keys(item).sort().join();
if(key == prev_key) continue;
prev_key = key;
result.push(item);
}
console.log(result);
var arr =
[
{"mw://HOME_BIN":{"position":0}},
{"mw://diagnosis_HOME":{"position":3}},
{"mw://HOME_BIN":{"position":3}},
{"mw://HOME_BIN":{"position":3}}
];
var nArr = [];
arr.forEach((ar,index) => {
if(index === arr.length - 1) {
nArr.push(ar);
return;
}
if(JSON.stringify(ar) !== JSON.stringify(arr[index+1])){
nArr.push(ar);
}
})
console.log(nArr);
You can use JSON.stringify to compare whole objects instead of using single key, for your scalability

Count the number of unique occurrences in an array that contain a specific string with Javascript

Here is my javascript array:
arr = ['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots'];
With Javascript, how can I count the total number of all unique values in the array that contain the string “dots”. So, for the above array the answer would be 3 (blue-dots, orange-dots, and red-dots).
var count = 0,
arr1 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf('dots') !== -1) {
if (arr1.indexOf(arr[i]) === -1) {
count++;
arr1.push(arr[i]);
}
}
}
you check if a certain element contains 'dots', and if it does, you check if it is already in arr1, if not increment count and add element to arr1.
One way is to store element as key of an object, then get the count of the keys:
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
console.log(Object.keys(arr.reduce(function(o, x) {
if (x.indexOf('dots') != -1) {
o[x] = true;
}
return o
}, {})).length)
Try this something like this:
// Create a custom function
function countDots(array) {
var count = 0;
// Get and store each value, so they are not repeated if present.
var uniq_array = [];
array.forEach(function(value) {
if(uniq_array.indexOf(value) == -1) {
uniq_array.push(value);
// Add one to count if 'dots' word is present.
if(value.indexOf('dots') != -1) {
count += 1;
}
}
});
return count;
}
// This will print '3' on console
console.log( countDots(['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots']) );
From this question, I got the getUnique function.
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
then you can add a function that counts ocurrences of a string inside an array of strings:
function getOcurrencesInStrings(targetString, arrayOfStrings){
var ocurrencesCount = 0;
for(var i = 0, arrayOfStrings.length; i++){
if(arrayOfStrings[i].indexOf(targetString) > -1){
ocurrencesCount++;
}
}
return ocurrencesCount;
}
then you just:
getOcurrencesInStrings('dots', initialArray.getUnique())
This will return the number you want.
It's not the smallest piece of code, but It's highly reusable.
var uniqueHolder = {};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
arr.filter(function(item) {
return item.indexOf('dots') > -1;
})
.forEach(function(item) {
uniqueHolder[item] ? void(0) : uniqueHolder[item] = true;
});
console.log('Count: ' + Object.keys(uniqueHolder).length);
console.log('Values: ' + Object.keys(uniqueHolder));
Try this code,
arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
sample = [];
for (var i = 0; i < arr.length; i++) {
if ((arr[i].indexOf('dots') !== -1) && (sample.indexOf(arr[i]) === -1)){
sample.push(arr[i]);
}
}
alert(sample.length);
var arr = [ "blue-dots", "blue", "red-dots", "orange-dots", "blue-dots" ];
var fArr = []; // Empty array, which could replace arr after the filtering is done.
arr.forEach( function( v ) {
v.indexOf( "dots" ) > -1 && fArr.indexOf( v ) === -1 ? fArr.push( v ) : null;
// Filter if "dots" is in the string, and not already in the other array.
});
// Code for displaying result on page, not necessary to filter arr
document.querySelector( ".before" ).innerHTML = arr.join( ", " );
document.querySelector( ".after" ).innerHTML = fArr.join( ", " );
Before:
<pre class="before">
</pre>
After:
<pre class="after">
</pre>
To put this simply, it will loop through the array, and if dots is in the string, AND it doesn't already exist in fArr, it'll push it into fArr, otherwise it'll do nothing.
I'd separate the operations of string comparison and returning unique items, to make your code easier to test, read, and reuse.
var unique = function(a){
return a.length === 0 ? [] : [a[0]].concat(unique(a.filter(function(x){
return x !== a[0];
})));
};
var has = function(x){
return function(y){
return y.indexOf(x) !== -1;
};
};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
var uniquedots = unique(arr.filter(has('dots')));
console.log(uniquedots);
console.log(uniquedots.length);

Create an array [n,[v,..,z]] from a list of key-value pairs

I have this input sample:
var c1 = "s_A_3";
var c2 = "s_B_10";
var c3 = "s_B_9";
var c4 = "s_C_18";
var c5 = "s_C_19";
var c6 = "s_C_20";
Which can easily be concatenated to:
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
And I want to convert this to a multidimensional array like this:
var groupArray = [["A",[3]],["B",[10,9]],["C",[18,19,20]]];
It's like a kind of card-sorting. How can I achieve this?
Maybe something like this:
function makeGroups(arr) {
var result = [], prev;
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (prev !== x[0]) {
prev = x[0];
result.push([prev, []]);
}
result[result.length - 1][1].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
The above method assumes the groups will be contiguous (e.g. all B_ elements appear together). In case your input may be out of order, you can tweak this algorithm to still group all elements together regardless of where they appear in the input:
function makeGroups(arr) {
var result = [], keys = {};
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (!(x[0] in keys)) {
keys[x[0]] = [];
result.push([x[0], keys[x[0]]]);
}
keys[x[0]].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","C_18","C_19","C_20","B_9"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
When you need to mention "key value pairs" in a JS program, it's usually most appropriate to use... key value pairs =D.
function solution(input) {
var kvp = {},
result = [];
input.forEach(function (el) {
var cut = el.split("_"),
alpha = cut[0],
numeric = cut[1],
elsWithSameAlpha = kvp[alpha] = kvp[alpha] || [];
elsWithSameAlpha.push(numeric);
});
Object.keys(kvp).forEach(function (key) {
result.push([key, kvp[key]]);
});
return result;
}

Get element on any level of an object in Javasscript

Given the following:
var a = JSON.parse('{"fst":"data1","snd":{"ind2":"data2"}}');
var index = "fst";
var res = a[index]; //res = data1
var index2 = "????";
var res2 = a[index2]; //res = data2
what should I put on index2 so res2 equals data2?
I'm looking for a generic syntax that would let me grab an element at ANY level of the parsed json, just by modifying the index string.
(I'm looping through a list of elements from different places/levels of a json derived object to build a table)
Any help would be much appreciated
You need a function for that
function deepAccess( obj, str ) {
var parts = str.split("."),
cur = obj;
for( var i = 0; i < parts.length; ++i ) {
cur = cur[parts[i]];
}
return cur;
}
var index = "fst";
deepAccess( a, index ); //"data1"
index = "snd.ind2";
deepAccess( a, index ); //"data2"
You're accessing a property of a property, and the syntax reflects this:
var res = a['snd']['ind2'];
There is no way to directly grab the "nested" property directly. If you're allowed to change the original object, you could add shortcut accessors for each object:
//Credit goes to Esailja for the original
function deepAccess(obj) {
function nestedAccess(o, level) {
if (typeof o == "object") {
var level = level || "";
for (p in o) {
if (o.hasOwnProperty(p)) {
if (level && typeof(o[p]) != "object") {
obj[level + "." + p] = o[p];
}
nestedAccess(o[p], (level ? level + "." : "") + p);
}
}
}
}
nestedAccess(obj);
}
deepAccess(a);
a["snd.ind2"];
var someObject1 = {};
var someObject2 = {e01: '*', e02: {e03: '*', e04: '*'}, e05: '*'};
var someObject3 = {e01: {e02: {e03: '*'}}};
function setValueByPath(obj, path, value) {
var pathArray = path.split('.');
function goDownstears(o, chunk, val) {
var prop = chunk.shift();
if(!o.hasOwnProperty(prop)) o[prop] = {};
o[prop] = (chunk.length > 0) ? goDownstears(o[prop], chunk, val) : val;
return o;
}
obj = goDownstears(obj, pathArray, value);
}
setValueByPath(someObject1, 'e01.e02.e03', 'changed');
setValueByPath(someObject2, 'e02.e04', 'changed');
setValueByPath(someObject3, 'e01.e02.e03', 'changed');
setValueByPath(someObject3, 'e01.e02.e04', 'changed');
setValueByPath(someObject3, 'e02.e01.e01', 'changed');
console.log(someObject1);
console.log(someObject2);
console.log(someObject3);
My question was closed here set an object property with sugar like obj['level1.level2.leve3'] = value
See here http://jsfiddle.net/zafod/RDGwY
This issue is for setting a value, but you can just return an asked property througth iterations

Categories