0

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.

Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
indra257
  • 66
  • 3
  • 24
  • 50

3 Answers3

4

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)
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
2

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));
kind user
  • 40,029
  • 7
  • 67
  • 77
  • @AluanHaddad I had to use `apply` to be able to use this method on an array. I can do it with just `Math.max` but I will have to use the spread operator, to get the values out of the array. – kind user May 03 '17 at 19:20
  • I get it now, had a mental lapse. Thanks for the explanation though, perhaps add it your answer. – Aluan Haddad May 03 '17 at 19:29
0

Chucking out there a solution using the lodash maxBy function:

const maxColumnLocation = _.maxBy(data, 'ColumnLocation').ColumnLocation;
Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59