Example 1: I have an array like this
let arrayA = ["task A - memberA", "task A - memberB", "task B - memberA"]
I want to find out if two members doing the same task, then remove the task from the after one. The expected output of Example 1 should be:
arrayA = ["task A - memberA", "task B - memberA"]
Example 2:
let arrayA = [{task: "Task A", member: "MemberA"},{task: "Task A", member: "MemberB"},{task: "Task B", member: "MemberB"}]
Expected result 2:
arrayA = [{task: "Task A", member: "MemberA"},{task: "Task B", member: "MemberB"}]
Thank you,
Create a Set that keeps track of active tasks.
Then loop over the tasks array and extract the task by splitting the string and then if the task is not present in the Set then push it to the resultant array.
let tasks = ["task A - memberA", "task A - memberB", "task B - memberA"];
function getUniqueTasks(tasks) {
const activeTasks = new Set();
const uniqueTasks = [];
tasks.forEach((t) => {
const [task] = t.split(" - ");
if (!activeTasks.has(task)) {
uniqueTasks.push(t);
activeTasks.add(task);
}
});
return uniqueTasks;
}
console.log(getUniqueTasks(tasks));
If you're looking for a fancy one liner, then refer to the solution below:
const
data = ["task A - memberA", "task A - memberB", "task B - memberA"],
filterer = (s) => (d, _i, _a, t = d.split(" - ")[0]) => !s.has(t) && s.add(t),
result = data.filter(filterer(new Set()));
console.log(result);
Relevant documentations:
by using reduce method,
hint:
some method returns true or false
includes method return true or false
substr method return sub string from string i.e task name
refer MDN tutorials for more details
let arr = ["task A - memberA", "task A - memberB", "task B - memberA"]
let result = arr.reduce((pv,cv) => {
if(!pv.some(e => e.includes(cv.substr(0, cv.indexOf('-')).trim()))) pv.push(cv)
return pv
},[])
console.log(result)
for second example just replace
if(!pv.some(e => e.task.includes(cv.task.trim()))) pv.push(cv)
You could take a Set and a function for wanted unique part of the string.
const
getTask = s => s.split(' - ', 1)[0],
uniqueBy = fn => s => v => (w => !s.has(w) && s.add(w))(fn(v)),
data = ["task A - memberA", "task A - memberB", "task B - memberA"],
result = data.filter(uniqueBy(getTask)(new Set));
console.log(result);