I have 2 arrays and I would like to compare them and remove from the first arr 50% of the different values from the guide arr.
const arrToManipulate = [
{val: 'a', vis: true}, {val: 'b', vis: true}, {val: 'c', vis: true}, {val: 'd', vis: true}
];
const guideArr = ['a','b'];
my expected result should be:
const finalArr = [
{val: 'a', vis: true}, {val: 'b', vis: true}, {val: 'd', vis: true}
];
in my case it doesnt matter if value c or value d will remain, as long as only 50% of the different values will removed.
so far I tried to get a log of all the non-similar value but no success so far - but I get the same values twice of twice or not correct vlues.
for (let i = 0; i < arrToManipulate .length; i++) {
for ( let j = 0; j < guideArr .length; j++) {
if (arrToManipulate [i].val !== guideArr [j]) {
console.log(arrToManipulate[i].val)
}
}
}
Iterate the array you want to extract the matching values and half of the non-matching values. If the element is in the guide array add it. Otherwise add it 50%.
function cutDifferentValues(arrToManipulate, guideArr){
var j = 0;
var result = [];
for (var i = 0; i < arrToManipulate.length; i++){
if (guideArr.includes(arrToManipulate[i].val)){
result.push(arrToManipulate[i]);
continue;
}
else if (j % 2 == 0){
result.push(arrToManipulate[i]);
}
j++;
}
return result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.