I have a edit product page in react using node in the backend. Look at the following scenario. A product had 4 images before (a.png, b.png, c.png, d.png). I have updated by removing the a.png image and added new image e.png. so right now I have (b.png, c.png, d.png, e.png) images available. In order to update I do not want to unlink all (a.png, b.png, c.png, d.png). as b.png, c.png, d.png is still existing. I just want to remove a.png and add d.png. By which javascript logic can I establish creating an array which will only consist of the array of image I want to remove in this case ["a.png"]
let prevImages = ['a.png', 'b.png', 'c.png','d.png']
let images = ['b.png','c.png', 'd.png', 'e.png']
CodePudding user response:
To accomplush you wanna get is
difference = prevImages.filter(item => images.indexOf(item) < 0);
CodePudding user response:
I think you want something like this:
let prevImages = ['a.png', 'b.png', 'c.png','d.png']
let images = ['b.png','c.png', 'd.png', 'e.png']
const imagesToRemove = prevImages.filter(img => !images.includes(img));
const imagesToAdd = images.filter(img => !prevImages.includes(img));
console.log(`Images to remove: ${imagesToRemove.join(',')}`);
console.log(`Images to add: ${imagesToAdd.join(',')}`);