So I've been trying to remove numbers of an arrayA that are in an arrayB. But if a number is only one time in that arrayB, and more than one time in that arrayA, i want my function to remove only ONE of them.
My function looks like it could work but it doesn't...
the expected output is : 1,3,3,4,5
let arrayA = [1,1,2,3,3,3,4,4,5]
let arrayB = [1,2,3,4]
function remove(arrayB,arrayA){
//newarray is the result array i want to get
let newarray = [];
//counter will controll if a number is more than one time in my arrayA
let counter = [];
arrayA.forEach(function(n){
//if a number of my arrayA is not in my arrayB
if(arrayB.indexOf(n) == -1){
newarray.push(n);
}
//if a number of my arrayB is only one time in my arrayA
else if(a.indexOf(n) == a.lastIndexOf(n)){
}
//if a number is more than one time but its the first one we meet
else if(a.indexOf(n) !== a.lastIndexOf(n) && counter.includes(n) == false){
//push it into the counter array so we'll know we already had this number
counter.push(n)
}
// if it's the second time we have to keep it and get it in the newarray
else {
newarray.push(n);
}
})
document.write(newarray)
}
-
What is the expected output?Faly– Faly2018年05月11日 13:06:07 +00:00Commented May 11, 2018 at 13:06
-
i'll update with the expected output immediately, sorryNoémie Carette– Noémie Carette2018年05月11日 13:07:31 +00:00Commented May 11, 2018 at 13:07
-
Looks like you want stackoverflow.com/questions/1187518/…Jagdeep Singh– Jagdeep Singh2018年05月11日 13:10:47 +00:00Commented May 11, 2018 at 13:10
-
are the arrays sorted?Nina Scholz– Nina Scholz2018年05月11日 13:13:03 +00:00Commented May 11, 2018 at 13:13
-
@NinaScholz yes they are, but i don't think it really makes a difference.Noémie Carette– Noémie Carette2018年05月11日 13:26:57 +00:00Commented May 11, 2018 at 13:26
3 Answers 3
A single loop is enough. Loop arrayB and remove the found element from arrayA. indexOf will always stop at the first hit, which makes it fairly simple:
let arrayA = [1,1,2,3,3,3,4,4,5];
let arrayB = [1,2,3,4];
arrayB.forEach(e => arrayA.splice(arrayA.indexOf(e), 1));
console.log(arrayA);
Comments
You can loop through arrayB and remove the same value in arrayA:
var arrayA = [1,1,2,3,3,3,4,4,5];
var arrayB = [1,2,3,4];
arrayB.forEach(b => {
var index = arrayA.findIndex(a => a === b);
arrayA = [ ...arrayA.slice(0, index), ...arrayA.slice(index + 1)];
});
console.log(arrayA);
1 Comment
findIndex, and no reason for using complex destructuring.You could take a hash table and count down the occurence of the not wanted items.
var arrayA = [1, 1, 2, 3, 3, 3, 4, 4, 5],
arrayB = [1, 2, 3, 4],
hash = arrayB.reduce((o, v) => (o[v] = (o[v] || 0) + 1, o), Object.create(null));
console.log(arrayA.filter(v => !hash[v] || !hash[v]--));
For sorted arrays, as given, you could use an index as closure over the arrayB.
var arrayA = [1, 1, 2, 3, 3, 3, 4, 4, 5],
arrayB = [1, 2, 3, 4];
console.log(arrayA.filter((i => v => v !== arrayB[i] || !++i)(0)));