tabulator column visible, using function to decide column visibility [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to set the column visibility though a function, to check if a value in the cell is true, then the column is visible, else it is hidden,
am using tabulator JS
this part is based on a column value in the rows , as below
My plan was, if the value of ageRange > 25, the column is visible, but with no success, I tried the below code:
const table = new Tabulator("#example-table", {
data: tabledata,
columns: [{
title: "Name",
field: "name",
width: 200
},
{
title: "Gender",
field: "gender",
visible: false
},
{
title: "Age",
formatter: AgeIcon,
width: 40,
headerSort: false,
visible: function (e, cell) {
return cell.getRow().getData().ageRange > 25;
}
},
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.4.1/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.4.1/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>

set the column visibility though a function
According to the Tabulator documentation, the visible property on the column definition does not take a function--only a boolean value.
Use the hideColumn function to hide the column based on the data.
See this snippet for an example.
//define data
const tabledata = [{
id: 1,
name: "Oli Bob",
location: "United Kingdom",
gender: "male",
rating: 1,
col: "red",
dob: "14/04/1984"
},
{
id: 2,
name: "Mary May",
location: "Germany",
gender: "female",
rating: 2,
col: "blue",
dob: "14/05/1982"
},
{
id: 3,
name: "Christine Lobowski",
location: "France",
gender: "female",
rating: 0,
col: "green",
dob: "22/05/1982"
},
{
id: 4,
name: "Brendon Philips",
location: "USA",
gender: "male",
rating: 1,
col: "orange",
dob: "01/08/1980"
},
{
id: 5,
name: "Margret Marmajuke",
location: "Canada",
gender: "female",
rating: 5,
col: "yellow",
dob: "31/01/1999"
},
{
id: 6,
name: "Frank Harbours",
location: "Russia",
gender: "male",
rating: 4,
col: "red",
dob: "12/05/1966"
},
{
id: 7,
name: "Jamie Newhart",
location: "India",
gender: "male",
rating: 3,
col: "green",
dob: "14/05/1985"
},
{
id: 8,
name: "Gemma Jane",
location: "China",
gender: "female",
rating: 0,
col: "red",
dob: "22/05/1982"
},
{
id: 9,
name: "Emily Sykes",
location: "South Korea",
gender: "female",
rating: 1,
col: "maroon",
dob: "11/11/1970"
},
{
id: 10,
name: "James Newman",
location: "Japan",
gender: "male",
rating: 5,
col: "red",
dob: "22/03/1998"
},
];
//define table
const table = new Tabulator("#example-table", {
data: tabledata,
columns: [{
title: "Name",
field: "name",
width: 200
},
{
title: "Gender",
field: "gender",
visible: false
},
{
title: "Rating",
field: "rating",
width: 80,
bottomCalc: "avg",
visible: true
},
{
title: "Favourite Color",
field: "col"
},
{
title: "Date Of Birth",
field: "dob",
align: "center",
sorter: "date"
}
],
});
const ratings = tabledata.map(d => d.rating);
const averaveRating = ratings.reduce((p, c) => p + c) / ratings.length;
//hide the "rating" column if low average rating
if (averaveRating < 2.5) {
table.hideColumn("rating");
console.log(`Average rating is ${averaveRating}, column hidden`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.4.1/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.4.1/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>

Related

Can you skip a level in a nested object without knowing the key in Javascript?

Hi I have this object
15: {
name: "Jane",
age: 43,
children: {
32: {
name: "Janette",
age: 24,
children: {
487: {
name: "Alex",
age: 3,
children: [],
},
166: {
name: "Marcus",
age: 1,
children: [],
},
},
},
},
},
104: {
name: "Eric",
age: 24,
children: [],
},
};
I want to remove or and skip through directly to the children. But it is a random produced key value "between". How can I make a new array or just modify it since I don't know what the key will be?
I want it to be like this:
var object = [
{
name: "Jane",
age: 43,
children: [
{
name: "Janette",
age: 24,
children: [
{
name: "Alex",
age: 3,
children: [],
},
{
name: "Marcus",
age: 1,
children: [],
},
],
},
],
},
{
name: "Eric",
age: 43,
children: [],
},
];
So as you see in the code, the ID with numbers are gone in that object that I want to make. Can you jump directly to the children if they exist?
you can do something like this
const stripKeys = data => Object.values(data)
.map(d => ({
...d,
children: stripKeys(d.children)
}))
const data = {
15: {
name: "Jane",
age: 43,
children: {
32: {
name: "Janette",
age: 24,
children: {
487: {
name: "Alex",
age: 3,
children: [],
},
166: {
name: "Marcus",
age: 1,
children: [],
},
},
},
},
},
104: {
name: "Eric",
age: 24,
children: [],
},
};
console.log(stripKeys(data))

count object based on status and shop using javascript?

I have the following JSON array I want to create a new field in every object which will be a count of the object
we have to get a count based on status, shop, and name(ownerDetails)
How can I achieve this and I have added my expected output below
var items = [
{
"id": 1,
"status": "ORANGE",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 2,
"status": "GREEN",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 3,
"status": "ORANGE",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 4,
"status": "YELLOW",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 5,
"status": "RED",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id":6,
"status": "GREEN",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 7,
"status": "GREEN",
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}]
},
{
"id": 8,
"status": "ORANGE",
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}]
},
{
"id": 9,
"status": "YELLOW",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 10,
"status": "GREEN",
"Shop":"EFG",
"ownerDetails":[ {"name":"test3","address":"test3"}]
},
{
"id": 11,
"status": "GREEN",
"Shop":"EFG",
"ownerDetails":[ ]
}
]
Expected output: So based on each shop, status and name(ownerDetails) we have to count the object
[
{
"id": 1,
"status": "ORANGE"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 2,
"status": "GREEN"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 3,
"status": "ORANGE"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 4,
"status": "YELLOW"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 5,
"status": "RED"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 1
},
{
"id":6,
"status": "GREEN"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 7,
"status": "GREEN"
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}],
"Count": 1
},
{
"id": 8,
"status": "ORANGE"
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}],
"Count": 1
},
{
"id": 9,
"status": "YELLOW"
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}],
"Count": 2
},
{
"id": 10,
"status": "GREEN"
"Shop":"EFG"
"ownerDetails":[ {"name":"test3","address":"test3"}],
"Count": 1
},
{
"id": 11,
"status": "GREEN",
"Shop":"EFG",
"ownerDetails":[ ],
"Count": 1
}
]
Plese see demo
Thanks #Nico_ for your and #Parth Ravalhelp
Below code is not working when "ownerDetails":[ ] and I got the below error Cannot read properties of undefined (reading 'name') in console
code :
const itemsWithCount = items.map(item => ({
...item,
Count: items.filter(({ status, Shop ,ownerDetails: [{ name }]}) => item.status === status && item.Shop === Shop && item.ownerDetails[0].name === name).length
}));
console.log(itemsWithCount)
Deconstruction of a not defined object
/**
* Problem: The deconstructed object is not defined.
*
* This will throw: TypeError: Cannot read properties of undefined (reading 'name')
*
* This is roughly equivalent of doing const { name } = undefined
*/
const [{ name }] = [];
/**
* Solution: Assign a default value when the deconstructed object is not defined.
*
* If the deconstructing object is undefined,
* assign an empty object as the default value
*/
const [{ name } = {}] = [];
Accessing a property of an undefined object
If you don't check that the ownerDetails array isn't empty before comparing item.ownerDetails[0].name === name, you might end up trying to access a property of an object that doesn't exist. This will result in a TypeError like above.
To deal with this situation, you must:
Verify that there is at least one element in item.ownerDetails;
Verify that name property exists on the first element;
If the tests passed, returns the value of the name property for the first element of ownerDetails. Otherwise, you must provide a default value.
Working example
const items = [
{ id: 1, status: 'ORANGE', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 2, status: 'GREEN', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 3, status: 'ORANGE', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 4, status: 'YELLOW', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 5, status: 'RED', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 6, status: 'GREEN', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 7, status: 'GREEN', Shop: 'XYZ', ownerDetails: [{ name: 'test2', address: 'test2' }] },
{ id: 8, status: 'ORANGE', Shop: 'XYZ', ownerDetails: [{ name: 'test2', address: 'test2' }] },
{ id: 9, status: 'YELLOW', Shop: 'ABC', ownerDetails: [{ name: 'test1', address: 'test1' }] },
{ id: 10, status: 'GREEN', Shop: 'EFG', ownerDetails: [{ name: 'test3', address: 'test3' }] },
{ id: 11, status: 'GREEN', Shop: 'EFG', ownerDetails: [] }
];
const itemsWithCount = items.map(item => ({
...item,
/**
* If the first element of ownerDetails is not defined,
* assign an empty object as the default value for the first
* element of ownerDetails array.
*/
Count: items.filter(({ status, Shop, ownerDetails: [{ name } = {}] }) =>
item.status === status &&
item.Shop === Shop &&
(
(
/**
* 1. Check if ownerDetails is not empty.
*/
item.ownerDetails.length &&
/**
* 2. Check if the first element of item.ownerDetails has a name property.
*
* ESLint best practice:
* ------------------------------------------------------
* Disallow calling some Object.prototype methods directly on objects.
* For more details, see https://eslint.org/docs/rules/no-prototype-builtins
* ------------------------------------------------------
*/
Object.prototype.hasOwnProperty.call(item.ownerDetails[0], 'name') &&
/**
* 3. Accessing and returning name property.
*/
item.ownerDetails[0].name
/**
* Else, compare undefined with name property.
*/
) || undefined
) === name
).length
}));
console.log(itemsWithCount)
Output
[
{ Count: 2, id: 1, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'ORANGE' },
{ Count: 2, id: 2, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'GREEN' },
{ Count: 2, id: 3, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'ORANGE' },
{ Count: 2, id: 4, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'YELLOW' },
{ Count: 1, id: 5, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'RED' },
{ Count: 2, id: 6, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'GREEN' },
{ Count: 1, id: 7, ownerDetails: [{ address: 'test2', name: 'test2' }], Shop: 'XYZ', status: 'GREEN' },
{ Count: 1, id: 8, ownerDetails: [{ address: 'test2', name: 'test2' }], Shop: 'XYZ', status: 'ORANGE' },
{ Count: 2, id: 9, ownerDetails: [{ address: 'test1', name: 'test1' }], Shop: 'ABC', status: 'YELLOW' },
{ Count: 1, id: 10, ownerDetails: [{ address: 'test3', name: 'test3' }], Shop: 'EFG', status: 'GREEN' },
{ Count: 1, id: 11, ownerDetails: [], Shop: 'EFG', status: 'GREEN' }
]
var items = [{
"id": 1,
"status": "ORANGE",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 2,
"status": "GREEN",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 3,
"status": "ORANGE",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 4,
"status": "YELLOW",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 5,
"status": "RED",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 6,
"status": "GREEN",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 7,
"status": "GREEN",
"Shop": "XYZ",
"ownerDetails": [{
"name": "test2",
"address": "test2"
}]
},
{
"id": 8,
"status": "ORANGE",
"Shop": "XYZ",
"ownerDetails": [{
"name": "test2",
"address": "test2"
}]
},
{
"id": 9,
"status": "YELLOW",
"Shop": "ABC",
"ownerDetails": [{
"name": "test1",
"address": "test1"
}]
},
{
"id": 10,
"status": "GREEN",
"Shop": "EFG",
"ownerDetails": [{
"name": "test3",
"address": "test3"
}]
}
];
var mapData = items.map((data) => {
var getList = items.filter(word => word.Shop == data.Shop).length;
return {
id: data.id,
status: data.status,
Shop: data.Shop,
text: data.ownerDetails,
Count: getList
};
});
console.log(mapData);
Note:- Map Data and Counted Similar Shops....
Looping through the array for each element is not an efficient way to go about it. A cleaner and more efficient way would be to create an object with keys as the combination of the values you need to compare.
Following should help:
let items = [
{"id":1,"status":"ORANGE","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":2,"status":"GREEN","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":3,"status":"ORANGE","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":4,"status":"YELLOW","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":5,"status":"RED","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":6,"status":"GREEN","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":7,"status":"GREEN","Shop":"XYZ","ownerDetails":[{"name":"test2","address":"test2"}]},
{"id":8,"status":"ORANGE","Shop":"XYZ","ownerDetails":[{"name":"test2","address":"test2"}]},
{"id":9,"status":"YELLOW","Shop":"ABC","ownerDetails":[{"name":"test1","address":"test1"}]},
{"id":10,"status":"GREEN","Shop":"EFG","ownerDetails":[{"name":"test3","address":"test3"}]},
{"id":11,"status":"GREEN","Shop":"EFG","ownerDetails":[]}
]
let itemMap = {};
for (const item of items) {
const key = `${item.Shop}_${item.status}_${item.ownerDetails[0]?.name}`;
if (itemMap[key]) {
itemMap[key].push({ ...item, Count: itemMap[key][0].Count+1 });
for (const matchedItem of itemMap[key]) {
matchedItem.Count++;
}
} else {
itemMap[key] = [{ ...item, Count: 1 }];
}
}
let processedItems = [];
for (const items of Object.values(itemMap)) {
for (const item of items) {
processedItems.push(item);
}
}
console.log(processedItems);
Note: This would not work if the order of the objects is to be preserved
You can do it with a map to loop through your array (you need to add some coma before the "Shop" by the way.
const items = [
{
"id": 1,
"status": "ORANGE",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 2,
"status": "GREEN",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 3,
"status": "ORANGE",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 4,
"status": "YELLOW",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 5,
"status": "RED",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id":6,
"status": "GREEN",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 7,
"status": "GREEN",
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}]
},
{
"id": 8,
"status": "ORANGE",
"Shop":"XYZ",
"ownerDetails":[ {"name":"test2","address":"test2"}]
},
{
"id": 9,
"status": "YELLOW",
"Shop":"ABC",
"ownerDetails":[ {"name":"test1","address":"test1"}]
},
{
"id": 10,
"status": "GREEN",
"Shop":"EFG",
"ownerDetails":[ {"name":"test3","address":"test3"}]
},
{
"id": 11,
"status": "GREEN",
"Shop":"EFG",
"ownerDetails":[ ]
}
];
const itemsWithCount = items.map(item => ({
...item,
Count: items.filter(({ status, Shop }) => item.status === status && item.Shop === Shop).length
}));
For each item of your array, you keep the current value of the item (the ...item) and you add a Count property, that will get the count for this item by filtering the array to keep only the item that have the same status and shop and you get the length of that array.

I need to find the total salary which is the sum of commission and salary (JS)

Given the array:
let Employee = [{
id: 1123,
department: "Sales",
['basic salary']: 10000,
commission: 3000,
}, {
id: 1223,
department: "HR",
['basic salary']: 9100,
commission: 1,
}, {
id: 1323,
department: "IT",
['basic salary']: 12000,
commission: 33000,
}, {
id: 1423,
department: "Support",
['basic salary']: 10000,
commission: 1000,
}, {
id: 1523,
department: "HR",
['basic salary']: 910000,
commission: 2300,
}, {
id: 1123,
department: "Sales",
['basic salary']: 91000,
commission: 2300,
}];
So my question is, how can I calculate the total for each department, if the total = the sum of salary and commission?
const moneyForDepartment = {};
Employee.forEach((emp) => {
if (moneyForDepartment[emp.department] === undefined) {
moneyForDepartment[emp.department] = 0;
}
moneyForDepartment[emp.department] += emp.commission + emp["basic salary"];
})
console.log(moneyForDepartment);
you just need to loop and build an object with key that represent total amount of each department

tabulator is not a function

I am following quick start guide in tabulator(v4.2+) - http://tabulator.info/docs/4.2/quickstart which worked as expected, when I included a button click function inside my html script I get .tabulator is not a function error and the table variable seems to be printing undefined in the browser console,
When i try to print in the browser console it returns table object but not console.log from the code
var tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
col: "red",
dob: ""
}, {
id: 2,
name: "Mary May",
age: "1",
col: "blue",
dob: "14/05/1982"
}, {
id: 3,
name: "Christine Lobowski",
age: "42",
col: "green",
dob: "22/05/1982"
}, {
id: 4,
name: "Brendon Philips",
age: "125",
col: "orange",
dob: "01/08/1980"
}, {
id: 5,
name: "Margret Marmajuke",
age: "16",
col: "yellow",
dob: "31/01/1999"
}, ];
table = new Tabulator("#example-table", {
height: 200,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
}, {
title: "Age",
field: "age",
align: "left",
formatter: "progress"
}, {
title: "Favourite Color",
field: "col"
}, {
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}, ],
rowClick: function(e, row) {
alert("Row " + row.getData().id + " Clicked!!!!");
},
});
console.log(table);
$("#savebtn").click(function(e) {
e.preventDefault()
console.log(table)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
<div class="form-group">
<label for="comment2"></label>
<div id="example-table"></div>
</div>
<input type="submit" value="Save" id="savebtn" />
The error is coming in this part of the code when the button click happens, table object is printing as undefined ?
$("#savebtn").click(function(e) {
e.preventDefault()
console.log(table)
});
Use var keyword
var table = new Tabulator(
const tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
col: "red",
dob: ""
}, {
id: 2,
name: "Mary May",
age: "1",
col: "blue",
dob: "14/05/1982"
}, {
id: 3,
name: "Christine Lobowski",
age: "42",
col: "green",
dob: "22/05/1982"
}, {
id: 4,
name: "Brendon Philips",
age: "125",
col: "orange",
dob: "01/08/1980"
}, {
id: 5,
name: "Margret Marmajuke",
age: "16",
col: "yellow",
dob: "31/01/1999"
}, ];
const table = new Tabulator("#example-table", {
height: 200,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
}, {
title: "Age",
field: "age",
align: "left",
formatter: "progress"
}, {
title: "Favourite Color",
field: "col"
}, {
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}, ],
rowClick: function(e, row) {
alert("Row " + row.getData().id + " Clicked!!!!");
},
});
console.log(table.getData());
$("#savebtn").click(function(e) {
// e.preventDefault()
// console.log(table.getData());
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
</head>
<body>
<div class="form-group">
<label for="comment2"></label>
<div id="example-table"></div>
</div>
<input type="submit" value="Save" id="savebtn" />
</body>
</html>

Sum column tabulator based on condition

I am trying to sum column value in tabulator with specific condition and follow this Custom Calculation Function
What I tried so far:
$(document).ready(function() {
function getSum(total, num) {
return total + num;
}
var adultCalc = function(values, data, calcParams) {
var tempvalue = [];
data.forEach(function(data) {
var count = data.age * data.qty;
tempvalue.push(count);
});
console.log('array', tempvalue);
console.log('total', tempvalue.reduce(getSum));
/*return tempvalue;*/
}
var tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
qty: "1",
dob: ""
},
{
id: 3,
name: "Christine Lobowski",
age: "42",
qty: "1",
dob: "22/05/1982"
},
{
id: 4,
name: "Brendon Philips",
age: "35",
qty: "2",
dob: "01/08/1980"
},
{
id: 5,
name: "Margret Marmajuke",
age: "16",
qty: "0",
dob: "31/01/1999"
},
{
id: 5,
name: "Marmajuke",
age: "17",
qty: "0",
dob: "31/01/1999"
},
{
id: 4,
name: "Philips",
age: "27",
qty: "0",
dob: "01/08/1980"
}
];
var table = new Tabulator("#example-table", {
height: 205,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
},
{
title: "Age",
field: "age",
bottomCalc: adultCalc
},
{
title: "Qty",
field: "qty"
},
{
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.1.4/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.1.4/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>
My formula is : age * qty push it into array and total it.
I'm success to get the value what i want and push it into array, but the problem is i can't sum the array with array reduce function.
I got this error
TypeError: reduce of empty array with no initial value
My problem just to get total sum of array.
Can someone tell me what's wrong with my code?
Thanks.
You need to provide initial value to reduce
console.log('total', tempvalue.reduce(getSum,0));
first time when you use reduce you have an empty array and which is causing reduce to produce an error. you can pass initial value and it should work as expected.
Note: If initialValue isn't provided, reduce() will execute the
callback function starting at index 1, skipping the first index. If
initialValue is provided, it will start at index 0.
$(document).ready(function() {
function getSum(total, num) {
return total + num;
}
var adultCalc = function(values, data, calcParams) {
var tempvalue = [];
data.forEach(function(data) {
var count = data.age * data.qty;
tempvalue.push(count);
});
console.log('array', tempvalue);
console.log('total', tempvalue.reduce(getSum,0));
/*return tempvalue;*/
}
var tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
qty: "1",
dob: ""
},
{
id: 3,
name: "Christine Lobowski",
age: "42",
qty: "1",
dob: "22/05/1982"
},
{
id: 4,
name: "Brendon Philips",
age: "35",
qty: "2",
dob: "01/08/1980"
},
{
id: 5,
name: "Margret Marmajuke",
age: "16",
qty: "0",
dob: "31/01/1999"
},
{
id: 5,
name: "Marmajuke",
age: "17",
qty: "0",
dob: "31/01/1999"
},
{
id: 4,
name: "Philips",
age: "27",
qty: "0",
dob: "01/08/1980"
}
];
var table = new Tabulator("#example-table", {
height: 205,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
},
{
title: "Age",
field: "age",
bottomCalc: adultCalc
},
{
title: "Qty",
field: "qty"
},
{
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.1.4/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.1.4/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>
It can be done even easier. And don't forget the second parameter (initial value) of Array.reduce method.
$(document).ready(function() {
function getSum(total, num) {
return total + num;
}
var adultCalc = function(values, data, calcParams) {
return data.map(function(d) {
return d.age * d.qty;
})
.reduce(getSum, 0);
}
//or even in ES6 style
const qtyCalc = (values, data, calcParams) =>
data.map(d => d.age * d.qty)
.reduce((t, n) => t + n * 2, 0);
var tabledata = [{
id: 1,
name: "Oli Bob",
age: "12",
qty: "1",
dob: ""
},
{
id: 3,
name: "Christine Lobowski",
age: "42",
qty: "1",
dob: "22/05/1982"
},
{
id: 4,
name: "Brendon Philips",
age: "35",
qty: "2",
dob: "01/08/1980"
},
{
id: 5,
name: "Margret Marmajuke",
age: "16",
qty: "0",
dob: "31/01/1999"
},
{
id: 5,
name: "Marmajuke",
age: "17",
qty: "0",
dob: "31/01/1999"
},
{
id: 4,
name: "Philips",
age: "27",
qty: "0",
dob: "01/08/1980"
}
];
var table = new Tabulator("#example-table", {
height: 205,
data: tabledata,
layout: "fitColumns",
columns: [{
title: "Name",
field: "name",
width: 150
},
{
title: "Age",
field: "age",
bottomCalc: adultCalc
},
{
title: "Qty",
field: "qty",
bottomCalc: qtyCalc
},
{
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
}
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.1.4/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.1.4/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>

Categories

Resources