I have two arrays in my react component as follows ...
const [Selected, setSelected] = React.useState([]);
const [NonSelected, setNonSelected] = React.useState([]);
const Tmp_Selected = [
{ "Metric": "AAA", "Weight": 10, "Value": "xxx" },
{ "Metric": "BBB", "Weight": 20, "Value": "xx1" },
{ "Metric": "CCC", "Weight": 30, "Value": "xx2" },
];
const Tmp_NonSelected = [
{ "Metric": "DDD", "Weight": 5, "Value": "yy" },
{ "Metric": "EEE", "Weight": 15, "Value": "zz" },
{ "Metric": "FFF", "Weight": 25, "Value": "cc" },
];
React.useEffect(() => {
setSelected(Tmp_Selected);
setNonSelected(Tmp_NonSelected);
}, [location]);
There is a function which gets passed just Metric and Weight related values. Based on that I need to move each object which matches both criteria from the NonSelected to the Selected array.
const MoveValues = (Metric='DDD', Weight=5) => {
}
The expected result for the above two default measures is equal to this ...
const Tmp_Selected = [
{ "Metric": "AAA", "Weight": 10, "Value": "xxx" },
{ "Metric": "BBB", "Weight": 20, "Value": "xx1" },
{ "Metric": "CCC", "Weight": 30, "Value": "xx2" },
{ "Metric": "DDD", "Weight": 5, "Value": "yy" },
];
const Tmp_NonSelected = [
{ "Metric": "EEE", "Weight": 15, "Value": "zz" },
{ "Metric": "FFF", "Weight": 25, "Value": "cc" },
];
The feature the OP actually relies on for solving the task is an array mutating
rejectfunctionality.Such a function (or method) does accept a callback similar to
filter, where the callback's parameters areitem, idx, arr, ..., and its return value is expected to be a boolean type or at least truthy/falsy. Upon the result of each invocation of the callback, while iterating the to be operated array entirely, arejectimplementation willspliceeach matching item from the operated array, thus mutating the latter. Each spliced item gets collected in the implementation'sresultarray which also is therejectfunction's return value.Thus, a possible implementation of the OP's
moveValuesfunction can be accomplished as easy as this ...