React-table add total as first row - reactjs

I'm using react-table 6.9.2. I want to be able to add a row at the top (right under the header) that displays the total of each column.
Here is my function that just outputs a table with static values:
function App() {
const data = [
{
one: 2,
two: 10.4,
three: 10.1,
four: 54,
five: 5,
six: 5,
seven: 10,
eight: 10,
nine: 10
},
{
one: 1,
two: 10.4,
three: 10.1,
four: 54,
five: 5,
six: 5,
seven: 10,
eight: 10,
nine: 10
}
];
return (
<div className="App">
<ReactTable
data={data}
showPagination={false}
columns={[
{
Header: "Sales Overview",
columns: [
{
Header: "one",
id: "one",
accessor: "one",
show: true
},
{
Header: "two",
accessor: "two",
show: true
},
{
Header: "three",
id: "three",
accessor: "three",
show: true
},
{
Header: "four",
id: "four",
accessor: "four",
show: true
},
{
Header: "five",
id: "five",
accessor: "five",
show: true
},
{
Header: "six",
id: "six",
accessor: "six",
show: true
},
{
Header: "seven",
id: "seven",
show: true,
accessor: "seven"
},
{
Header: "eight",
id: "eight",
show: true,
accessor: "eight"
},
{
Header: "nine",
id: "nine",
accessor: "nine",
show: true
}
]
}
]}
loading={false}
minRows={1}
className="-striped -highlight"
/>
</div>
);
}
Is there a way I can add a total row at the top? Even if I get the total value of each column sent within data, can I order it to always display the total row at the top?
In case it's any help, I have also created a sandbox to show the table: https://codesandbox.io/s/2vz3z741op
Thanks in advance!

You can just add a totals entry to the data array:
https://codesandbox.io/s/qv7vjpr69
const getTotals = (data, key) => {
let total = 0;
data.forEach(item => {
total += item[key];
});
return total;
};
function App() {
const data = [
{
one: "first row",
two: 10.4,
...
},
{
one: "second row",
two: 10.4,
...
}
];
data.unshift({
one: "totals",
two: getTotals(data, "two"),
three: getTotals(data, "three"),
four: getTotals(data, "four"),
five: getTotals(data, "five"),
six: getTotals(data, "six"),
seven: getTotals(data, "seven"),
eight: getTotals(data, "eight"),
nine: getTotals(data, "nine")
});

Related

Modifying select for product variation in React Js

In a small ecommerce project (sourcing data from WooCommerce) in ReactJs i have a variable product
Besides all the product data i got two array object representing the product variations, one contains all the available attribute and options:
nodes: Array(3)
0:
id: "d2VpZ2h0OjMxOldlaWdodA=="
name: "Weight"
options: Array(2)
0: "250gr"
1: "500gr"
position: 0
variation: true
visible: true
1:
id: "cm9hc3Q6MzE6Um9hc3Q="
name: "Roast"
options: Array(3)
0: "Light"
1: "Medium"
2: "Dark"
position: 1
variation: true
visible: true
2:
id: "cGFja2FnaW5nOjMxOlBhY2thZ2luZw=="
name: "Packaging"
options: Array(2)
0: "Card"
1: "Tin"
position: 2
variation: true
visible: true
I save this one in a state and use it to build the select (3 select in this case)
then i have an array of object which contans all the available combinations, with price, id and so on:
nodes: Array(5)
0:
attributes:
nodes: Array(3)
0: {id: "NDB8fHdlaWdodHx8MjUwZ3I=", name: "weight", value: "250gr"}
1: {id: "NDB8fHJvYXN0fHxNZWRpdW0=", name: "roast", value: "Medium"}
2: {id: "NDB8fHBhY2thZ2luZ3x8Q2FyZA==", name: "packaging", value: "Card"}
id: "cHJvZHVjdF92YXJpYXRpb246NDA="
price: "€7,00"
variationId: 40
1:
attributes:
nodes: Array(3)
0: {id: "Mzh8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "Mzh8fHJvYXN0fHxEYXJr", name: "roast", value: "Dark"}
2: {id: "Mzh8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246Mzg="
price: "€12,00"
variationId: 38
2:
attributes:
nodes: Array(3)
0: {id: "Mzd8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "Mzd8fHJvYXN0fHxNZWRpdW0=", name: "roast", value: "Medium"}
2: {id: "Mzd8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246Mzc="
price: "€12,00"
variationId: 37
3:
attributes:
nodes: Array(3)
0: {id: "MzZ8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "MzZ8fHJvYXN0fHxMaWdodA==", name: "roast", value: "Light"}
2: {id: "MzZ8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
id: "cHJvZHVjdF92YXJpYXRpb246MzY="
price: "€12,00"
variationId: 36
4:
attributes:
nodes: Array(3)
0: {id: "MzR8fHdlaWdodHx8MjUwZ3I=", name: "weight", value: "250gr"}
1: {id: "MzR8fHJvYXN0fHxMaWdodA==", name: "roast", value: "Light"}
2: {id: "MzR8fHBhY2thZ2luZ3x8Q2FyZA==", name: "packaging", value: "Card"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246MzQ="
price: "€7,00"
variationId: 34
Basically, when i select something on any select, the other select shoould filter based on the avaialble variations: if i select 250gr as weight, the Dark Roast and the Tin Packaging sould be removed from their select since they arent combinable with 250gr; if i switch back to 500gr (or to "no option selected") they should reappear in the same place as they were before.
on the basic WooCommerce product page it already works this way (you can check its behaviour here: https://shop.popland.it/prodotto/coffee-bean/) but replicating it in ReactJs its harder than i was thinking.
At the moment im stuck on loop that generate the select with an empty onChange handler:
const [attr, setAttr] = useState(product.attributes);
<div>
{attr.nodes.map((attribute, l) => {
return (
<div key={l}>
<span>{attribute.name}</span>
<select
id={attribute.name}
onChange={handleChange}
data-attribute_name={`attribute_${attribute.name}`}
>
<option>Select option</option>
{attribute.options.map((option, o) => {
return (
<option key={o} value={option}>
{option}
</option>
);
})}
</select>
</div>
);
})}
</div>
Any suggetion/help on how to go on from here?
here is my solution.
/src/hooks.js
import { useState } from "react";
import { filterVariations, formatVariations } from "./helpers";
export function useVariations(product) {
const [state, setState] = useState({});
const filteredVariations = filterVariations(
product?.variations?.nodes,
state,
);
const formatedVariations = formatVariations(
filteredVariations,
product?.variations?.nodes,
);
return [formatedVariations, state, setState];
}
/src/helpers.js
export function filterVariations(variations, state) {
if (Object.keys(state).length === 0) {
return variations;
}
return Object.keys(state)?.reduce((accStateVars, currStateVar) => {
return accStateVars.reduce((accVars, currVar) => {
const filteredAttrsByName = currVar?.attributes?.nodes?.filter(
(attr) => currStateVar === attr?.name,
);
const withSelected = currVar?.attributes?.nodes?.findIndex(
(attr) => attr?.attributeId === state?.[currStateVar]?.value,
);
return [
...accVars,
{
attributes: {
nodes:
withSelected >= 0
? currVar?.attributes?.nodes
: filteredAttrsByName,
},
},
];
}, []);
}, variations);
}
export function formatVariations(filteredVariations, variations) {
const defaultSelects = variations?.reduce(
(accVars, currVar) => ({
...accVars,
...currVar?.attributes?.nodes?.reduce(
(accAttrs, currAttr) => ({ ...accAttrs, [currAttr.name]: {} }),
{},
),
}),
{},
);
return filteredVariations.reduce((accVars, currVar) => {
const filteredAttrs = currVar?.attributes?.nodes?.reduce(
(accAttrs, currAttr) => {
const exists =
0 <=
accVars[currAttr.name]?.options?.findIndex(
(option) => option.value === currAttr.attributeId,
);
return {
...accAttrs,
[currAttr.name]: {
placeholder: currAttr.label,
options: exists
? accVars[currAttr.name]?.options || []
: [
...(accVars[currAttr.name]?.options || []),
{ label: currAttr.value, value: currAttr.attributeId },
],
},
};
},
{},
);
return { ...accVars, ...filteredAttrs };
}, defaultSelects);
}
/src/App.js
import "./styles.css";
import Select from "react-select";
import { useVariations } from "./hooks";
const product = {
variations: {
nodes: [
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY5MHx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 304,
id: "NTY5MHx8cGFfY29sb3J8fGdyYXBoaXRl",
label: "Color",
value: "Graphite",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY5MHx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY5MHx8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 255,
id: "NTY4Nnx8cGFfc2l6ZXx8MTAtc3BlYWtlcg==",
label: "Size",
value: '10" Speaker',
},
{
name: "pa_color",
attributeId: 67,
id: "NTY4Nnx8cGFfY29sb3J8fGJlaWdl",
label: "Color",
value: "Beige",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY4Nnx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 337,
id: "NTY4Nnx8cGFfcGFsbGV0fHxwZWFjaA==",
label: "Pallet",
value: "Peach",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 255,
id: "NTY4N3x8cGFfc2l6ZXx8MTAtc3BlYWtlcg==",
label: "Size",
value: '10" Speaker',
},
{
name: "pa_color",
attributeId: 439,
id: "NTY4N3x8cGFfY29sb3J8fGZhdGFsLWFwcGxl",
label: "Color",
value: "Fatal Apple",
},
{
name: "pa_flavor",
attributeId: 319,
id: "NTY4N3x8cGFfZmxhdm9yfHx2YW5pbGxh",
label: "Flavor",
value: "Vanilla",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY4N3x8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY4OHx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 67,
id: "NTY4OHx8cGFfY29sb3J8fGJlaWdl",
label: "Color",
value: "Beige",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY4OHx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 337,
id: "NTY4OHx8cGFfcGFsbGV0fHxwZWFjaA==",
label: "Pallet",
value: "Peach",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY4OXx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 436,
id: "NTY4OXx8cGFfY29sb3J8fGJlbGdyYXZlcw==",
label: "Color",
value: "Belgraves",
},
{
name: "pa_flavor",
attributeId: 319,
id: "NTY4OXx8cGFfZmxhdm9yfHx2YW5pbGxh",
label: "Flavor",
value: "Vanilla",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY4OXx8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
],
},
};
export default function App() {
const [selects, state, setState] = useVariations(product);
function onChange(select, value) {
const newState = {
...state,
[select]: { ...value, name: select },
};
if (!value) {
delete newState[select];
}
setState(newState);
}
return (
<div className="App">
{Object.keys(selects).map((select) => (
<Select
isClearable
key={selects[select].placeholder}
placeholder={selects[select].placeholder}
// value={state[select]}
onChange={(o) => onChange(select, o)}
options={selects[select].options}
/>
))}
</div>
);
}
Playground

Unique Array by comparing elements of array React JS

I have this array
array = [
{id: "one", title: "new 1"},
{id: "two", parent_id: "132132", title: "new 2"},
{id: "three", parent_id: "132132", title: "new 3"},
{id: "four", parent_id: "132132", title: "new 1"},
{id: "one", parent_id: "132132", title: "new 1"}
]
We need
array = [
{id: "two", parent_id: "132132", title: "new 2"},
{id: "three", parent_id: "132132", title: "new 3"},
{id: "four", parent_id: "132132", title: "new 1"},
{id: "one", parent_id: "132132", title: "new 1"}
]
We need to compare elements to get unique array with different avoiding other elements
I have tried using this method
uniqueArray = (arr) => {
return arr.filter((e, i, arr) => arr.findIndex(e2 => Object.keys(e2).every(prop => e2[prop] === e[prop])) === i);
};
I prefer Array.reduce for this kind of things:
const filteredArr = arr.reduce((acc, current) => {
const exists = acc.find(item => item.id === current.id);
if (!exists) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
If I understand you correctly, you want to return object without the property of parentId. If so you can use this.
array.filter(arr => arr.hasOwnProperty("parentId"))

Filter Array of Object from another Array of Object

Currently I'm filtering data based from questions that have checked property value equals to true..
const data = [
{Name: "foo", X1: "1", X2: "1", Other: "Test1"},
{Name: "bar", X1: "2",X2: "2",Other: "Test2"},
{Name: "test",X1: "2",X2: "3",Other: "Test3"}
];
const questions = [{rows: {text: "Text 1", checked: true,fields: "1",column: "X1"}
}, {rows: {text: "Text 2", checked: true,fields: "2",column: "X1"}
}, {rows: {text: "Text 3", checked: false,fields: "1",column: "X2"}
}, {rows: {text: "Text 4", checked: false,fields: "2",column: "X2"}
}, {rows: {text: "Text 5", checked: false,fields: "3",column: "X2"}
}];
console.log(questionArr);
// console.log(dataArr);
const res = data.filter(d => questions.find(f => d[f.rows.column] === f.rows.fields && f.rows.checked));
which works but does not work when filtering the actual data below. I think there's a slight difference between the question object and the actual question object below.. What should be my filter code when accessing these kind of structure ?
I think this is what you're looking for. I matched the data structure to the image in your question. Let me know if I missed something.
const data = [
{ Name: "foo", X1: "1", X2: "1", Other: "Test1" },
{ Name: "bar", X1: "2", X2: "2", Other: "Test2" },
{ Name: "test", X1: "2", X2: "3", Other: "Test3" }
];
const questions = [
{ rows: [{ text: "Text 1", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 2", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 3", checked: false, fields: "1", column: "X2" }] },
{ rows: [{ text: "Text 4", checked: false, fields: "2", column: "X2" }] },
{ rows: [{ text: "Text 5", checked: false, fields: "3", column: "X2" }] }
];
const result = data.filter(function(item){
return questions.some(function(question){
return question.rows.some(function(row){
return (row.checked && item[row.column] === row.fields);
});
});
});
console.log(result);
The compact version
const result = data.filter((item) => questions.some((question) => question.rows.some((row) => (row.checked && item[row.column] === row.fields))));
With perf in mind
const data = [
{ Name: "foo", X1: "1", X2: "1", Other: "Test1" },
{ Name: "bar", X1: "2", X2: "2", Other: "Test2" },
{ Name: "test", X1: "2", X2: "3", Other: "Test3" }
];
const questions = [
{ rows: [{ text: "Text 1", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 2", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 3", checked: false, fields: "1", column: "X2" }] },
{ rows: [{ text: "Text 4", checked: false, fields: "2", column: "X2" }] },
{ rows: [{ text: "Text 5", checked: false, fields: "3", column: "X2" }] }
];
const result = {};
for(let a = 0, b = data.length; a < b; a++){
const item = data[a];
for(let c = 0, d = questions.length; c < d; c++){
const rows = questions[c].rows;
for(let e = 0, f = rows.length; e < f; e++){
const row = rows[e];
if(row.checked && item[row.column] === row.fields){
result[item.Name] = item;
break;
}
}
}
}
// this could be replaced with Object.values(result);
const matches = [];
for(let match in result){
matches.push(result[match]);
}
// not supported by IE yet
// Object.values(result);
console.log(matches);

Find items in the array based on the inner array condition

How to find id in an array that is inside of an array of objects
Example:
let arrayobjects = [{
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}];
How can I find the id of the word "two" ?
If you need more than one item, you can filter the array via Array#filter, check if property description for each item contains word two via Array#includes (ES7), then map the result to get only id of those items using Array#map.
let arrayobjects = [
{ id: 1, name: "oinoin", description: ["one", "two", "three"] },
{ id: 2, name: "zatata", description: ["four", "five", "six"] }
];
const ids = arrayobjects.filter(item => item.description.includes('two'))
.map(item => item.id);
console.log(ids);
If you have only one item, you can just use Array#find and do same checking
let arrayobjects = [
{ id: 1, name: "oinoin", description: ["one", "two", "three"] },
{ id: 2, name: "zatata", description: ["four", "five", "six"] }
];
const item = arrayobjects.find(item => item.description.includes('two'));
console.log(item.id);
This snippet might be what you are looking for
arrayobjects.filter( ele => ele.description.includes("two")).map(ele => ele.id)
output :[1]
There may be more efficient way, but i some how find a solution. iterate through the array and match the array item.
var arrayobjects = [{ id: 1, name: "oinoin", description: ["one", "two", "three"]}, { id: 2, name: "zatata", description: ["four", "five", "six"]}];
arrayobjects.forEach(item => {
if(item.description.indexOf('two') != -1 ){
console.log(item.id)
}
})
You can try with indexOf too
arrayobjects.filter(f=>f.description.indexOf('two')>-1)[0].id
let arrayobjects = [
{
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}
];
console.log(arrayobjects.filter(f=>f.description.indexOf('two')>-1)[0].id);
Note
.filter returns an array. So if multiple items are found with two in description then you do not use index [0]. This is just an example of one item in array.
For examples sake, here is a version with old javascript.
var arrayobjects = [
{
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}
];
function findId (desc, arr) {
var idx, arrObjLen = arr.length, results = [];
// Iterate through the first array
for (idx = 0; idx < arrObjLen; idx ++) {
// If the value exists in the 'description' array
if (arr[idx].description.indexOf(desc) > -1) {
// Add it to the results array
results.push(arr[idx].id)
}
}
return results;
}
console.log('Results:', findId('five', arrayobjects));
You could also use Array#reduce if you want to minimise the amount of code you're using:
const arrayobjects = [
{
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}
];
console.log(
arrayobjects.reduce((col, { id, description }) =>
// If description contains the desired value
description.includes('two')
// Add the id to the collector array
? [ ...col, id ] : col, [])
);

How can I merge columns in UI-grid?

Is there any way to merge the columns of UI-grid to be appear as continuous row (without any column line in between). I have tried this
merge columns in ui grid
but this causes me loss of row data at row number number 1. Even more I want every alternate row to be merged.
Here is my Html
<div id="grid" ui-grid="gridOptions" ui-grid-move-columns ui-grid-resize-columns ui-grid-auto-resize class="grid"></div>
Here is my js code for grid
$scope.gridOptions = {
enableColumnResizing: true,
enableRowHeaderSelection: false,
enableGridMenu: true,
enableHorizontalScrollbar: 0,
enableVerticalScrollbar: 2,
enableColumnMenus: false,
enableRowSelection: true,
columnDefs: [
{
name: 'Code',
field: 'Code',
}, {
name: 'Title',
field: 'Title',
}, {
name: 'Visits',
field: 'Visit',
}, {
name: 'UsedVisits',
field: 'usedVisits',
}, {
name: 'Pending Visits',
field: 'pendingVisits',
}, {
name: 'Available Visits',
field: 'availableVisits',
}, {
name: 'Start Date',
field: 'StartDate',
}, {
name: 'End Date',
field: 'EndDate',
}, {
name: 'Status',
field: 'Status',
}
]
};
Please suggest me something,
Thank you
To implement it we can merge data while creating array for grid itself
using logic
originally we have array which we merge to show in grid so that in grid we can get merged data
$scope.myData = [{name: "1Abcd", age: "one", gender:2},
{name: "2Tom", age: "two", gender:1},
{name: "3Abcd", age: "three", gender:2},
{name: "4Abcd", age: "four", gender:2},
{name: "5Abcd", age: "five", gender:2},
{name: "6Abcd", age: "six", gender:2},
{name: "7Abcd", age: "seven", gender:2},
{name: "8Abcd", age: "eight", gender:2},
{name: "9Abcd", age: "nine", gender:2},
];
$scope.myDataNew =[] ;
for(var i=0;i<(($scope.myData.length/2)+1);i++){
var tempObj ={};
if($scope.myData[i*2] && $scope.myData[i*2].name && $scope.myData[i*2+1] &&$scope.myData[i*2+1].name){
tempObj.name =$scope.myData[i*2].name+$scope.myData[i*2+1].name ;
}
else if($scope.myData[i*2] && $scope.myData[i*2].name && !$scope.myData[i*2+1] ){
tempObj.name =$scope.myData[i*2].name;
}
if($scope.myData[i*2] && $scope.myData[i*2].age && $scope.myData[i*2+1] &&$scope.myData[i*2+1].age){
tempObj.age =$scope.myData[i*2].age+$scope.myData[i*2+1].age ;
}else if($scope.myData[i*2] && $scope.myData[i*2].age && !$scope.myData[i*2+1] )
{
tempObj.age =$scope.myData[i*2].age;
}
$scope.myDataNew.push(tempObj);
}
here is code pen for completed implementation
http://codepen.io/vkvicky-vasudev/pen/LRPNyL
If ant change required feel free to inform me

Resources