I am trying to filter an array by compare it to another array and return an element that is missing from the second array.
The same element may occur multiple times, and each occurrence should either have a corresponding occurrence in the second array or be considered missing from the second array.
Here is an example.
example 1:
const participant = ['mario', 'zelda', 'ken', 'sonic'];
const completion = ['zelda', 'ken', 'mario'];
// return 'sonic' because the name is not inside of completion array
example 2:
const participant = ['mario', 'zelda', 'ken', 'sonic'];
const completion = ['mario', 'ken', 'sonic'];
// return 'zelda', the name is not inside of the array
example 3:
const participant = ['mario', 'zelda', 'ken', 'mario'];
const completion = ['mario', 'zelda', 'ken'];
// this time return 'mario' because only one 'mario' is inside of the array (think of this as another person with the same name)
And this is how I try to solve it
// iteration participant array inside completion array and if completion array find first same element inside participant array, remove that element
const solution = (participant, completion) => {
completion.find(c => {
participant.forEach((p, idx) => {
if (c === p) {
participant.splice(idx, idx+1)
}
})
})
}
However this code only works in example 1 and 2, example 3 returns an empty array.
Thought using find method finds first element inside of an array that matches with element I want to find but it does not work way I expected.
Did I misuse find method?
Nick :
You can use Array.findIndex to find any value in completion that is also in participant and delete it from that array. This will only delete the first occurrence of the value in participant, giving the correct result for your third example:\n\r\n\r\nconst solution = (participant, completion) => {\n completion.forEach(c => {\n idx = participant.findIndex(p => p == c);\n if (idx >= 0) {\n participant.splice(idx, idx + 1)\n }\n });\n return participant;\n};\n\nlet participant = ['mario', 'zelda', 'ken', 'sonic'];\nlet completion = ['zelda', 'ken', 'mario'];\n\nconsole.log(solution(participant, completion));\n\nparticipant = ['mario', 'zelda', 'ken', 'sonic'];\ncompletion = ['mario', 'ken', 'sonic'];\n\nconsole.log(solution(participant, completion));\n\nparticipant = ['mario', 'zelda', 'ken', 'mario'];\ncompletion = ['mario', 'zelda', 'ken'];\n\nconsole.log(solution(participant, completion));",
2020-07-30T01:38:26