Biggest number of a field in Json data [duplicate] - javascript

This question already has answers here:
Finding the max value of an attribute in an array of objects
(21 answers)
Closed 5 years ago.
My Json data is as below
[{
"Name": "PieChart",
"Id": "1",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Name": "Calendar",
"Id": "2",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Name": "FavouriteFilter",
"Id": "3",
"ColumnLocation": "2",
"RowLocation": "0"
}, {
"Name": "FilterResults",
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "1"
}, {
"Name": "Watched",
"Id": "5",
"ColumnLocation": "1",
"RowLocation": "1"
}]
I need to find the highest number of the ColumnLocation of the above data. I need that information because I can draw my dashboard based on this number of columns.

Reduce:
const a = [{
"Name": "PieChart",
"Id": "1",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Name": "Calendar",
"Id": "2",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Name": "FavouriteFilter",
"Id": "3",
"ColumnLocation": "2",
"RowLocation": "0"
}, {
"Name": "FilterResults",
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "1"
}, {
"Name": "Watched",
"Id": "5",
"ColumnLocation": "1",
"RowLocation": "1"
}];
const r = a.reduce((a, c) => (c.ColumnLocation > a) ? c.ColumnLocation : a, 0);
console.log(r)

You could map every ColumnLocation key and use Math.max function to get the highest value.
var data = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}],
res = data.map(v => v.ColumnLocation);
//console.log(Math.max.apply(Math, res));
console.log(Math.max(...res));

Chucking out there a solution using the lodash maxBy function:
const maxColumnLocation = _.maxBy(data, 'ColumnLocation').ColumnLocation;

Related

Print object properties in javascript [duplicate]

This question already has answers here:
How to print all the properties of the object in javascript? [duplicate]
(2 answers)
Closed 5 months ago.
I am new to JavaScript and can't figure out how to do this. I tried using map and filter but could not able to put if condition.
find the records in above array which has gender is 0 and color is red
let student = [
{
"ID": "1",
"Name": "Senpai",
"Gender": "1",
"Class": "32",
"Strength": "0",
"Hairstyle": "1",
"Color": "Black"
},
{
"ID": "2",
"Name": "Yui Rio",
"Gender": "0",
"Class": "11",
"Strength": "0",
"Hairstyle": "2",
"Color": "Red"
},
{
"ID": "3",
"Name": "Yuna Hina",
"Gender": "1",
"Class": "12",
"Strength": "0",
"Hairstyle": "3",
"Color": "Red"
},
{
"ID": "4",
"Name": "Koharu Hinata",
"Gender": "0",
"Class": "21",
"Strength": "0",
"Hairstyle": "4",
"Color": "Green"
},
{
"ID": "5",
"Name": "Mei Mio",
"Gender": "1",
"Class": "22",
"Strength": "0",
"Hairstyle": "5",
"Color": "Blue"
}
];
const newArray = student.filter(s => {
if(s.Gender === "0" && s.Color === "Red"){
return s
}
})
or
const newArray = student.filter(s => s.Gender === "0" && s.Color === "Red")

Recreate the Json by identifying the missing values

I have a Json data that I need adjust before sending it to my component. My Json is as below. I need to identify the missing fields and move the below ones up.
[{
"Id": "a",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Id": "b",
"ColumnLocation": "0",
"RowLocation": "1"
},
{
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "3"
},
{
"Id": "c",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Id": "d",
"ColumnLocation": "1",
"RowLocation": "2"
}, {
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "0"
},
{
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "2"
}]
My required Json is:
[{
"Id": "a",
"ColumnLocation": "0",
"RowLocation": "0"
}, {
"Id": "b",
"ColumnLocation": "0",
"RowLocation": "1"
},
{
"Id": "4",
"ColumnLocation": "0",
"RowLocation": "2"
},
{
"Id": "c",
"ColumnLocation": "1",
"RowLocation": "0"
}, {
"Id": "d",
"ColumnLocation": "1",
"RowLocation": "1"
}, {
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "0"
},
{
"Id": "e",
"ColumnLocation": "2",
"RowLocation": "1"
}]
Here after (0,0), (0,1), property (0,2) is missing so I need to move it up and make it (0,2).. Same way after(1,0), property(1,1) is missing so it has to be (1,1).
I tried writing a custom function for this, but couldn't able to achieve it, so thought any map function that fits this scenario
I am getting gadgets information from the API. In some cases, some gadgets might be missing, so I need to pull there location up and draw the gadgets.
this.userService.getGadgets(id).subscribe(gadgets => { this.res = gadgets.map(function (v) { return v.ColumnLocation; });
// required logic ************/
for (let gadget of gadgets) {
this.dashboardsText = "";
switch (gadget.Name) {
You could store the last column and row, then check if it is not the same column, then reset row counter.
Then check if RowLocation is equal to row counter and if not set the new value.
Finally increment row counter.
var array = [{ Id: "a", ColumnLocation: "0", RowLocation: "0" }, { Id: "b", ColumnLocation: "0", RowLocation: "1" }, { Id: "4", ColumnLocation: "0", RowLocation: "3" }, { Id: "c", ColumnLocation: "1", RowLocation: "0" }, { Id: "d", ColumnLocation: "1", RowLocation: "2" }, { Id: "e", ColumnLocation: "2", RowLocation: "0" }, { Id: "e", ColumnLocation: "2", RowLocation: "2" }];
array.forEach(function (col, row) {
return function (o) {
if (col !== o.ColumnLocation) {
col = o.ColumnLocation;
row = 0;
}
if (+o.RowLocation !== row) {
o.RowLocation = row.toString();
}
row++;
}
}());
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use global variables instead if the closure, maybe this works for you.
var array = [{ Id: "a", ColumnLocation: "0", RowLocation: "0" }, { Id: "b", ColumnLocation: "0", RowLocation: "1" }, { Id: "4", ColumnLocation: "0", RowLocation: "3" }, { Id: "c", ColumnLocation: "1", RowLocation: "0" }, { Id: "d", ColumnLocation: "1", RowLocation: "2" }, { Id: "e", ColumnLocation: "2", RowLocation: "0" }, { Id: "e", ColumnLocation: "2", RowLocation: "2" }],
col,
row;
array.forEach(function (o) {
if (col !== o.ColumnLocation) {
col = o.ColumnLocation;
row = 0;
}
if (+o.RowLocation !== row) {
o.RowLocation = row.toString();
}
row++;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
};
var array, i;
array = [{"Id": "a","ColumnLocation": "0","RowLocation": "0"}, {
"Id": "b","ColumnLocation": "0", "RowLocation": "1"}]
i = array.length;
while (i--) {
if (!array[i].ColumnLocation) {
array.move(i, i+1);
}

Group objects by keys in JavaScript [duplicate]

This question already has answers here:
Group By and Sum using Underscore/Lodash
(6 answers)
Closed 6 years ago.
I have an array of objects. These objects have a property called "type".
[{
"id": "1",
"type": "Plane",
"date": "date",
"value": "10",
"another_value": "10"
},
{
"id": "1",
"type": "Plane",
"date": "date",
"value": "15",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
}]
Now, I have a table where I want to display this. I want to display it in two rows, one row for "Plane" and one row for "Car" and in that row I want like the total sum of (value, and another_value)
So I'm thinking this is easiest accomplished by somehow going through my original array of objects and grouping them by "type". So I'll get an array of all objects with the type "Car", and one with "Plane".
I have lodash available, then I also need to find a way to sum the values, so I can display it in my table, in a column on each row.
Any advice on how I can accomplish this?
You can do this with plain JavaScript, using methods like map() and filter():
const arr = [{
"id": "1",
"type": "Plane",
"date": "date",
"value": "10",
"another_value": "10"
},
{
"id": "1",
"type": "Plane",
"date": "date",
"value": "15",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
}]
const sum = (a, b) => Number(a) + Number(b)
const cars = arr.filter(x => x.type === 'Car')
const planes = arr.filter(x => x.type === 'Plane')
const carsValue = cars.map(x => x.value).reduce(sum)
const planesValue = planes.map(x => x.value).reduce(sum)
const carsAnotherValue = cars.map(x => x.another_value).reduce(sum)
const planesAnotherValue = planes.map(x => x.another_value).reduce(sum)
You could first group all the objects by type, and then reduce all the value and another_value:
var types = _.groupBy(array, 'type');
var result = _.mapValues(types, function(value, key) {
return _.reduce(value, function(memo, v) {
return memo + +v.value + +v.another_value;
}, 0);
});
var array = [{
"id": "1",
"type": "Plane",
"date": "date",
"value": "10",
"another_value": "10"
},
{
"id": "1",
"type": "Plane",
"date": "date",
"value": "15",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
}];
var types = _.groupBy(array, 'type');
var result = _.mapValues(types, function(value, key) {
return _.reduce(value, function(memo, v) {
return memo + +v.value + +v.another_value;
}, 0);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Another approach
var count = _.countBy(data, 'type');
var sum = _.reduce(data, function(total, obj) {
total[obj.type] += Number(obj.value);
return total;
}, {
Car: 0,
Plane: 0
});
var data = [{
"id": "1",
"type": "Plane",
"date": "date",
"value": "10",
"another_value": "10"
},
{
"id": "1",
"type": "Plane",
"date": "date",
"value": "15",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
},
{
"id": "1",
"type": "Car",
"date": "date",
"value": "25",
"another_value": "10"
}];
var count = _.countBy(data, 'type');
var sum = _.reduce(data, function(total, obj) {
total[obj.type] += Number(obj.value);
return total;
}, {
Car: 0,
Plane: 0
});
console.log(count['Plane']);
console.log(count['Car']);
console.log(sum['Plane']);
console.log(sum['Car']);
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>

Recursive iteration over dynamically nested object array

I am using angular JS and one of their examples:http://jsfiddle.net/furf/EJGHX/
I need to take the data when the update function occurs and add some values to it before I send to the server. (If doing this with angular instead of js would be better let me know)
I'm trying to get the 'parentid' and the 'index' and update the children.
Here is the data I'm looping through
{
"children": [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "1",
"children": [{
"id": "10",
"index": "0",
"text": "Grandstream GXP-21XX"
}, {
"id": "11",
"index": "1",
"text": "Polycom Soundstation/Soundpoint"
}, {
"id": "23",
"index": "2",
"text": "New Polycom"
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0",
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2",
"children": [{
"id": "9",
"index": "0",
"text": "Sonicwall"
}, {
"id": "12",
"index": "1",
"text": "Cisco"
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0",
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0",
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": "1",
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1",
"children": []
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7",
"children": [{
"id": "16",
"index": "0",
"text": "Porting and New Number Details"
}, {
"id": "18",
"index": "1",
"text": "Partner Setup"
}, {
"id": "19",
"index": "2",
"text": "test"
}, {
"id": "21",
"index": "3",
"text": "test"
}]
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0",
"children": []
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1",
"children": []
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2",
"children": []
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11",
"children": []
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3",
"children": []
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "2",
"children": []
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14",
"children": []
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15",
"children": []
}]
}
This is how I'm currently looping through it, but it only gets the first dimension
for (i = 0, l = data.length; i < l; i++) {
parentid = data[i].id == null ? '0' : data[i].id;
data[i].index = i;
if (data[i].children) {
if (data[i].children.length > 0) {
for (q = 0, r = data[i].children.length; q < r; q++) {
data[i].children[q].parentid = parentid;
data[i].children[q].index = q;
}
}
}
}
I found this one on another fiddle, but I don't know how I would grab the parentid or the index
$.each(target.children, function(key, val) { recursiveFunction(key, val) });
function recursiveFunction(key, val) {
actualFunction(key, val);
var value = val['children'];
if (value instanceof Object) {
$.each(value, function(key, val) {
recursiveFunction(key, val)
});
}
}
function actualFunction(key, val) {}
If I'm understanding you correctly, you want each 'child' to have a parentID (defined by its parent; 0 otherwise) and an index (based on its position within it sibling set).
function normalize(parent) {
if (parent && parent.children) {
for (var i = 0, l = parent.children.length; i < l; ++i) {
var child = parent.children[i];
child.index = i;
if (!child.parentId) child.parentId = parent.id || '0';
normalize(child);
}
}
}
normalize(data);
Recursion is calling function inside the same function. Your sample is not a recursion at all;
function runRecursive(input) {
for (var i = 0, l = input.length; i < l; i++) {
var current = input[i];
parentid = current.id == null ? '0' : current.id;
current.index = i;
if (current.children && current.children.length > 0) {
runRecursive(current.children);
};
};
};
runRecursive(data.children);
Also you should define i and l with var keyword, otherwise it will be located in window context and recursion logic will broken.
Though I don't get what is parentid variable for and why it defined outside visible code.

JS Prevent duplicates when using .push()

I grab a list of data from the server and I have to convert it.
Part of this is turning it into a 3 dimensional array. After the "myArr[i].children.push(temp);" it leaves copies of the objects that were pushed in the root of the array. Can I either push without copying or how would I delete these? (I have underscore js included, I know they have good array functions :))
for (var i = 0; i < myArr.length; i++) {
myArr[i].children = [];
for (var q = 0; q < myArr.length; q++) {
if (myArr[i].id == myArr[q].parentid) {
var temp = {
id: myArr[q].id,
index: myArr[q].index,
text: myArr[q].text
}
myArr[i].children.push(temp);
};
};
};
The Data
[{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "0"
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "1"
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2"
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0"
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "1"
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation\/Soundpoint",
"index": "2"
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1"
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7"
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0"
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1"
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2"
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11"
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3"
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "0"
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14"
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15"
}]
After it is formated:
{
"children": [{
"id": "5",
"parentid": "0",
"text": "Device Guides",
"index": "1",
"children": [{
"id": "10",
"index": "0",
"text": "Grandstream GXP-21XX"
}, {
"id": "11",
"index": "1",
"text": "Polycom Soundstation/Soundpoint"
}, {
"id": "23",
"index": "2",
"text": "New Polycom"
}]
}, {
"id": "6",
"parentid": "0",
"text": "Pre-Sales Evaluation",
"index": "0",
"children": []
}, {
"id": "7",
"parentid": "0",
"text": "Router Setup Guides",
"index": "2",
"children": [{
"id": "9",
"index": "0",
"text": "Sonicwall"
}, {
"id": "12",
"index": "1",
"text": "Cisco"
}]
}, {
"id": "9",
"parentid": "7",
"text": "Sonicwall",
"index": "0",
"children": []
}, {
"id": "10",
"parentid": "5",
"text": "Grandstream GXP-21XX",
"index": "0",
"children": []
}, {
"id": "11",
"parentid": "5",
"text": "Polycom Soundstation/Soundpoint",
"index": "1",
"children": []
}, {
"id": "12",
"parentid": "7",
"text": "Cisco",
"index": "1",
"children": []
}, {
"id": "15",
"parentid": "0",
"text": "Post-Sales Implementation Check List",
"index": "7",
"children": [{
"id": "16",
"index": "0",
"text": "Porting and New Number Details"
}, {
"id": "18",
"index": "1",
"text": "Partner Setup"
}, {
"id": "19",
"index": "2",
"text": "test"
}, {
"id": "21",
"index": "3",
"text": "test"
}]
}, {
"id": "16",
"parentid": "15",
"text": "Porting and New Number Details",
"index": "0",
"children": []
}, {
"id": "18",
"parentid": "15",
"text": "Partner Setup",
"index": "1",
"children": []
}, {
"id": "19",
"parentid": "15",
"text": "test",
"index": "2",
"children": []
}, {
"id": "20",
"parentid": "0",
"text": "test",
"index": "11",
"children": []
}, {
"id": "21",
"parentid": "15",
"text": "test",
"index": "3",
"children": []
}, {
"id": "23",
"parentid": "5",
"text": "New Polycom",
"index": "2",
"children": []
}, {
"id": "24",
"parentid": "0",
"text": "Test Markup",
"index": "14",
"children": []
}, {
"id": "25",
"parentid": "0",
"text": "test",
"index": "15",
"children": []
}]
}
Here you go
tree = {0: {children: []}}
data.forEach(function(x) {
x.children = tree[x.id] ? tree[x.id].children : [];
tree[x.id] = x;
if(!tree[x.parentid])
tree[x.parentid] = {children: []}
tree[x.parentid].children.push(x)
})
result = tree[0].children
This solution is linear (iterates over the array just once) and doesn't require any pre-sorting.
http://jsfiddle.net/U47WY/
and here's how to convert the tree back to the linear array:
function flatten(source) {
return source.reduce(function(a, x) {
var children = x.children;
delete x.children;
return a.concat([x], flatten(x.children))
}, []);
}
Following on from a friendly discussion in the comments :
var zeroObj = {"children":[]};
for (var i = 0; i < myArr.length; i++) {
if(myArr[i].parentid === 0) {
zeroObj.children.push(myArr[i]);
} else {
for (var q = 0; q < myArr.length; q++) {
if (myArr[i].parentid == myArr[q].id) {
myArr[q].children = myArr[q].children || [];
myArr[q].children.push(myArr[i]);
};
};
}
};

Categories