ag-grid-react: getSortModel is not a function - javascript

I'm trying to get sort model from ag-grid-react component using getSortModel() but I'm getting getSortModel is not a function
my code
onSortChanged={useCallback(e => console.log(e.api.getSortModel(), 'im from sort'))}
"#ag-grid-community/react": "27.3.0",
"#ag-grid-enterprise/all-modules": "27.3.0",

After spend some time found params.api.getSortModel() is deprecated after version 24.0.0.
Using Column state for get Sort model and set Sort model in the following way
getSortModel:
const onSortChanged = useCallback(() => {
const value = gridParams.columnApi.getColumnState().find(s => s.sort != null)
if (value) {
setSortModel([ value ])
} else {
setSortModel([])
}
}, [ gridParams, setSortModel ])
setSortModel:
useEffect(() => {
if (sortModel.length > 0) {
const curretSortModel = gridParams.columnApi.getColumnState()
const mergeSortModel = curretSortModel.map(o1 => sortModel.find(o2 => o2.colId === o1.colId) || o1)
gridParams.columnApi.setColumnState(mergeSortModel)
}
}, [gridParams, sortModel]

As per this plunkr, you can retrieve and apply sort with the following example: https://plnkr.co/edit/?open=index.jsx&preview
const sortByAthleteDesc = useCallback(() => {
gridRef.current.columnApi.applyColumnState({
state: [{ colId: 'athlete', sort: 'desc' }],
defaultState: { sort: null },
});
}, []);
const saveSort = useCallback(() => {
var colState = gridRef.current.columnApi.getColumnState();
var sortState = colState
.filter(function (s) {
return s.sort != null;
})
.map(function (s) {
return { colId: s.colId, sort: s.sort, sortIndex: s.sortIndex };
});
savedSort = sortState;
console.log('saved sort', sortState);
}, []);

Related

Update nested array using setState()

I want to setState() to edit parameter value which is in parameterData Array.
using setState method. If we can do this without any third part library like Immutabilty helper or lodash that would be great!
The Given state is
const[state,setState]= useState ([{
"id": 0,
"targets": {
"ageGender": {
"key":value
},
"parameterData": [
{
"id": 1,
"parameter": "Low",
"expression": "<",
"val": "10",
"indicator": "Select"
},
]
}
}])
I have tried this solution
where
idx = state index where object is situated index = index of
parameterData array to be changed event = event of change
const handleChangeTextParameter = (event, index, idx) => {
const { name, value } = event.target;
setState((prev) => {
const newState = prev.map((obj, index1) => {
let fil;
if (index1 === idx) {
fil = obj.targets.parameterData.map((data, indexOne) => {
if (indexOne === index) {
return { ...data, parameter: value };
}
return data;
});
const p = obj.targets.parameterData.map(
(obj) => fil.find((o) => o.id === obj.id) || obj
);
return { ...obj, targets: { ...obj.targets, parameterData: p } };
}
});
return newState;
});
};
Disclaimer: The state variables you defined are called state and setState, but in your handleChangeTextParameter you are using setTargets so I assume they are the same
I think the following should work:
setTargets((prev) => {
const newTargets = prev.map((object, objectIndex) => {
if (objectIndex !== idx) return object;
return {
...object,
targets: {
...object.targets,
parameterData: object.target.parameterData.map((data, dataIndex) => {
if (dataIndex !== index) return data;
return { ...data, parameter: value };
}),
},
};
});
return newTargets;
});

Node.js - How to merge objects inside an array based on condition?

In Node.js, I have 3 sets of data like
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"dailyData":159392.235451,
"dailyDataInUSC":255.284807
}
]
and
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"monthlyData":159392.235451,
"monthlyDataInUSC":255.284807
},
{
"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
"monthlyData":349392.455451,
"monthlyDataInUSC":655.234807
}
]
and
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"threeMonthsData":159392.235451,
"threeMonthsDataInUSC":255.284807
},
{
"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
"threeMonthsData":349392.455451,
"threeMonthsDataInUSC":655.234807
},
{
"userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3",
"threeMonthsData":6789392.455451,
"threeMonthsDataInUSC":905.655807
}
]
How can I combine this to one object based on userId(filter) inside an array.
Eg, output should be like
[
{
"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
"dailyData":159392.235451,
"dailyDataInUSC":255.284807,
"monthlyData":159392.235451,
"monthlyDataInUSC":255.284807,
"threeMonthsData":159392.235451,
"threeMonthsDataInUSC":255.284807
}
]
Please help me to achieve this.
A combination of spread, reduce and findIndex can be used to solve the problem.
Combine the original arrays into a single array using the spread operator.
Use reduce to group the elements by key (in this case userId)
Something like this :
const dailyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","dailyData":159392.235451,"dailyDataInUSC":255.284807}];
const monthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","monthlyData":159392.235451,"monthlyDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","monthlyData":349392.455451,"monthlyDataInUSC":655.234807}]
const triMonthlyData = [{"userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3","threeMonthsData":159392.235451,"threeMonthsDataInUSC":255.284807}, {"userId":"23fs6fds3-34k4-17de-3123-d2ec81e8aaf3","threeMonthsData":349392.455451,"threeMonthsDataInUSC":655.234807}, {"userId":"34sdf34-67j4-54nd-6763-d2ec81e8aaf3","threeMonthsData":6789392.455451,"threeMonthsDataInUSC":905.655807}]
const combinedData = [...dailyData, ...monthlyData, ...triMonthlyData].reduce((mergedResult, curElement) => {
let matchingElementIdx = mergedResult.findIndex(ele => ele.userId === curElement.userId);
if (matchingElementIdx !== -1) {
mergedResult[matchingElementIdx] = {...mergedResult[matchingElementIdx], ...curElement};
} else {
mergedResult = [...mergedResult, curElement];
}
return mergedResult;
}, []);
console.log(combinedData);
const aa = () => {
let aa = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
dailyData: 159392.235451,
dailyDataInUSC: 255.284807
}
];
let bb = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
monthlyData: 159392.235451,
monthlyDataInUSC: 255.284807
},
{
userId: "23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
monthlyData: 349392.455451,
monthlyDataInUSC: 655.234807
}
];
let cc = [
{
userId: "54c7f3ef-64d4-40de-8100-d2ec81e8aaf3",
threeMonthsData: 159392.235451,
threeMonthsDataInUSC: 255.284807
},
{
userId: "23fs6fds3-34k4-17de-3123-d2ec81e8aaf3",
threeMonthsData: 349392.455451,
threeMonthsDataInUSC: 655.234807
},
{
userId: "34sdf34-67j4-54nd-6763-d2ec81e8aaf3",
threeMonthsData: 6789392.455451,
threeMonthsDataInUSC: 905.655807
}
];
let newArrObj = aa;
bb.forEach(item => {
let index = newArrObj.findIndex(item1 => item1.userId === item.userId);
if (index === -1) {
newArrObj = [...newArrObj, item];
} else {
newArrObj[index] = { ...newArrObj[index], ...item };
}
});
cc.forEach(item => {
let index = newArrObj.findIndex(item1 => item1.userId === item.userId);
if (index === -1) {
newArrObj = [...newArrObj, item];
} else {
newArrObj[index] = { ...newArrObj[index], ...item };
}
});
console.log(newArrObj);
};

filter javascript array with a string array with multiple options

I have the following
let foo = ['public', 'private', 'secured', 'unsecured']; // value to search, it can be any combination
['secured', 'unsecured'], ['public', 'secured'] etc...
ARRAY
[
{ id: 1, isPrivate: true, isSecured: true },
{ id: 2, isPrivate: false, isSecured: true },
{ id: 3, isPrivate: true, isSecured: false },
{ ID: 4, isPrivate: false, isSecured: false }
];
[...items].filter(x => filterLabel(x, foo));
filterLabel(x, foo): boolean {
switch (foo[0]) {
case 'private': return x.isPrivate;
case 'public': return !x.isPrivate;
case 'secured': return x.isSecured;
case 'unsecured': return !x.isSecured;
default: return true;
}
This WORKS but it only filters by the first item of the array, i can't figure out how can i filter by using any combination of foo
Example: ['public', 'secured', 'unsecured'];
This would filter the array [...items] by item.isPrivate = false, item.isSecured = true, item.isSecured = false
Example: ['public', 'unsecured'];
This would filter the array [...items] by item.isPrivate = false, item.isSecured = false
Example: ['private', 'unsecured'];
This would filter the array [...items] by item.isPrivate = true, item.isSecured = false
PD: it can be solved by comparing any of the combination but i want to avoid this
const hash = new Set(foo);
const isPrivate = hash.has('private');
const isPublic = hash.has('public');
const isSecured = hash.has('secured');
const isUnsecured = hash.has('unsecured');
if (isPrivate && !isPublic && !isSecured && !isUnsecured) {
return item.isPrivate;
}
if (!isPrivate && isPublic && !isSecured && !isUnsecured) {
return !item.isPrivate;
}
if (!isPrivate && !isPublic && isSecured && !isUnsecured) {
return item.isSecured;
}
// and so on... with all the combinations
You could filter the array ba taking off contradictional labels and take for the rest a function.
const
filterLabel = filter => {
const
p = ['private', 'public'],
s = ['secured', 'unsecured'],
fn = {
private: ({ isPrivate }) => isPrivate,
public: ({ isPrivate }) => !isPrivate,
secured: ({ isSecured }) => isSecured,
unsecured: ({ isSecured }) => !isSecured
};
if (p.every(v => filter.includes(v)) filter = filter.filter(v => !p.includes(v));
if (s.every(v => filter.includes(v)) filter = filter.filter(v => !s.includes(v));
return o => filter.every(k => fn[k](o));
},
foo = ['public', 'private', 'secured', 'unsecured'],
result = items.filter(filterLabel(foo));

build array of only one property when condition is met

I am looking to filter an array of only one property from the filtered items.
I currently have:
let tools = permissions.filter(perm => {
if (perm.state === state) return perm.tool;
});
and that builds an array of perm objects. I am looking to have tools only filled with perm.tool. Is this possible?
example:
permissions =
[
{
state: 'NJ',
tool: 'email'
},
{
state: 'MA',
tool: 'print'
},
{
state: 'NJ',
tool: 'submit claim'
},
]
When state = 'NJ' , I am looking to get:
tools = ['email', 'submit claim']
What you want is a reduce
let tools = permissions.reduce((results, perm) => {
if (perm.state === state) {
results.push(perm.tool);
}
return results;
}, []);
You are probably looking for map after the filter:
let tools = permissions
.filter(perm => perm.state === state)
.map( el => el.tool );
let tools = (state) => {
return (permissions.reduce((acc, rec) => {
if (rec.state === state) {
return [...acc, rec.tool]
}
return [...acc]
}, [])
)
}
Here's a solution:
const permissions = [
{
state: 'NJ',
tool: 'email'
},
{
state: 'MA',
tool: 'print'
},
{
state: 'NJ',
tool: 'submit claim'
}
];
function getTools(state) {
const tools = [];
permissions.forEach(perm => {
if(perm.state == state) {
tools.push(perm.tool)
}
});
return tools;
}
console.log(getTools('NJ'));

How can I set the default option of dropdown while using choices library?

I am using Choices library for dropdown. What I need to do is to retain the selected value of dropdown and show it as soon as the page reloads before submitting. Right now I am able to store the value using sessionStorage. But how can I show it in the choices dropdown as the default option once the page reloads? I read the documentation but not able to figure out how to pass the default value.
document.querySelectorAll('.myDropdown').forEach(selectBox => {
choicesElements = new Choices(selectBox, { addItemText: ['Yes'], sortFn: (a, b) => a < b } );
selectBox.addEventListener('change', () => {
// code to populate choices
}
}
let marks_dropdown = document.querySelector('.myDropdown');
marks_dropdown_id.addEventListener("change",function() {
var choices_item_selectable = document.querySelector('.choices__item.choices__item--selectable')
storeSelectedItem(choices_item_selectable.innerText);
}
function storeSelectedItem(innertext) {
sessionStorage.setItem('innertext', innertext);
}
let innertext = sessionStorage.getItem('innertext');
if (innertext) {
let new_choices_item_selectable = document.querySelector('.choices__item.choices__item--selectable');
new_choices_item_selectable.innerText = innertext;
}
I solved the issue as below.
assignChoicesElements = () => {
document.querySelectorAll('.myDropdown').forEach(selectBox => {
choicesElements['some-key'] = new Choices(selectBox, { sortFn: (a, b) => a < b });
selectBox.addEventListener('change', () => {
let reqdValue = selectBox.value;
if(reqdValue != '') {
storeSelectedItem(reqdValue);
}
});
let elementsObject = {};
document.querySelectorAll('unMarked').forEach(unmarkedElement => {
elementsObject['some_key'] = //whatever value to be stored;
});
choicesElements['some-key'].clearStore();
choicesElements['some-key'].setChoices(getPossibleCombinations(elementsObject), 'value', 'label', false);
};
getPossibleCombinations = (jsonObject) => {
var possibleCombinations = {}
Object.entries(jsonObject).forEach(([key, value]) => {
var newPossibleCombinations = possibleCombinations
Object.entries(possibleCombinations).forEach(([key, value]) => {
let newValue = value
newPossibleCombinations['some-value'] = newValue
})
newPossibleCombinations['key'] = ['some-value']
possibleCombinations = newPossibleCombinations
})
var formatedPossibleCombinations = []
Object.entries(possibleCombinations).forEach(([key, value]) => {
// Here is the change. Get the stored value and while creating the list of values, add selected: true to the value if it is found in sessionStorage.
let sessionStorageValue = sessionStorage.getItem('stored_item')
if (sessionStorageValue) {
formatedPossibleCombinations.push({ label: key, value: value, selected: true })
}
})
return formatedPossibleCombinations
}
function storeSelectedItem(value) {
sessionStorage.clear();
sessionStorage.setItem('stored_item', value);
}
This code is more than required for the question. But I have added it just in case if anyone finds it useful.

Categories

Resources