When working in SQL, a common practice is to use a select statement with a group by clause followed by a having count = 1 condition.
select bID from tableA groupBy bID having count(*) = 1
My goal is to achieve the same functionality in TypeScript without relying on additional plugins or libraries. Ideally, I would like to implement this using pure JavaScript. After some research and exploration on Stack Overflow, I came across the .reduce function which seems suitable for my requirements.
However, I encountered compilation errors and type conversion issues when attempting to implement it. The errors mentioned implicit types and missing callback functions, making progress difficult.
Essentially, I am aiming to take an array, group its elements by a specific value, determine the count of each group, set a property to true for groups with a count of 1, and then terminate the process.
I found the following code snippet online:
groupByArray(xs, key) {
return xs.reduce(function (rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) { el.values.push(x); } else { rv.push({ key: v, values: [x] }); }
return rv;
}, []);
}
PS. Variable names such as "xs" and "rv" are commonly used in short form in this context, which can be confusing to beginners like me. Any explanation of these variables in the code snippet above would be greatly appreciated.
PPS. To illustrate, consider the following data example:
[{bID:1,isDeleted:false},{bID:1,isDeleted:true},{bID:2,isDeleted:false},{bID:1,isDeleted:true},{bID:3,isDeleted:false},{bID:3,isDeleted:false},{bID:4,isDeleted:false}]
The expected output based on the criteria described earlier should be [{bId:1,isDeleted:false}{bID:2,isDeleted:false},{bID:4,isDeleted:false}].
Below is the code snippet that I managed to make work:
var test = this.user2.scc.sA.reduce((a, b) => (a.Bid== b.Bid && !a.isDeleted) ? a : b);
Edit: Apologies for any confusion; I am writing in TypeScript, which is a superset of JavaScript. My initial mention of JavaScript was to emphasize avoiding dealing with prototypes in this scenario, as it is not considered best practice.