Rocky
Rocky

Reputation: 431

How to update or delete array of result in node

I got confuse, how to accomplished this task let me show code then issue

case 1

let arr1=[1,3]
let arr2=[1,2,3]

compare these 2 array if arr2 is greater then delete 2 from database

case 2

let arr1=[1,2,3]
let arr2=[1,2]

compare these 2 array if arr1 is greater, then insert 3 into database and return promise reject like resolve can anyone tell me what is best to achieve this.

Upvotes: 0

Views: 62

Answers (1)

Gautam Malik
Gautam Malik

Reputation: 146

solution to your problem

Step 1: find the difference in the two arrays lets say arr1 & arr2

Step 2: check if arr2.length is greater than delete the difference from the db

Step 3: if arr1.length is greater than insert difference in db

for Step 1 implement the below "difference" function:

Array.prototype.difference = function(arr) {
return this.filter(function(i) {return arr.indexOf(i) === -1;});
};
[1,2,3,4,5,6].diff( [3,4,5] );// return [1,2,6]
// here you capture the difference among arrays
let diffArray = arr1.difference(arr2);

for step 2 & step 3:

if(arr2.length > arr1.length){
  diffArray.forEach((element)=>{
   // your db deletion code comes here something like.....db.delete(element);
   return new Promise((resolve, reject) => {
      // db deletion code
      // return resolve(result)....if successfully inserted
      // reject(err).........if some error occurs
    })
   .then(result => result)
   .catch(err => err)
  });
// similarly
if (arr1.length >arr2.length){
   diffArray.forEach((element)=>{
   // your db insertion code comes here
   return new Promise((resolve, reject) => {
      // db insertion code
      // return resolve(result)....if successfully inserted
      // reject(err).........if some error occurs
    })
   .then(result => result)
   .catch(err => err)
  });
 }
}

Happy Coding :)

Upvotes: 1

Related Questions