Home > Mobile >  Javascript comparing two array of objects and remove the elements from first array based on second a
Javascript comparing two array of objects and remove the elements from first array based on second a

Time:09-29

I have to remove the elements from arrayOne which is exists in arrayTwo, but I have to remove those records which is matched at first occurrences only. Remaining records should present ass it is if still they matched.

let arrayOne = [
    {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'},
    {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'},
    {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'},
    {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'},
    {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'},
    {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'},
];

let arrayTwo = [
    {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'},
    {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'}
];


let result = arrayOne.filter(o1 => !arrayTwo.some(o2 => o1.variantnames == o2.variantnames));
console.log("result", result);

I know, we shold have to use findIndex to remove matched records from arrayOne but not able to get result.

Expected output should be

 result = [
     {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'},
     {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'},
     {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'},
     {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'},
 ];

CodePudding user response:

You could first create a Set of variantnames from arrayTwo, and then within your .filter() method, .delete() the variantnames from that set for each object in arrayOne. The .delete() method on a Set will return true if it deletes an item from the set, and false if otherwise. If you come across the same variantnames property again, it won't be in the set, so it can't be deleted and so the object will be kept:

const arrayOne = [ {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'}, {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'}, {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'}, {variantnames: 'chocolate', variantvalues: '15', forDate: '2022-09-29'}, {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'}, {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'}, ];
const arrayTwo = [ {variantnames: 'Testing', variantvalues: '20', forDate: '2022-09-29'}, {variantnames: 'free suger', variantvalues: '10', forDate: '2022-09-29'} ];

const variants = new Set(arrayTwo.map(({variantnames}) => variantnames));
const result = arrayOne.filter(o1 => !variants.delete(o1.variantnames));
console.log("result", result);

  • Related