12/18/19

Interesting Code Adventure With Compare the Array Of Objects

Recently i had some interesting task: The form i was working on - was supposed to update array of objects:


[
 {id: 1, framework: 'React'},
 {id: 2, framework: 'Angular'},
 {id: 3, framework: 'Vue'},
]

The problem was - the api has a support only for only one object at time and according to design - a form was planned to have only one "save" button (which suppose to trigger a batch saving)

 POST - api/framework
 DELETE - api/framework/:id
 UPDATE -api/framework/:id

So i needed to find a way to compare the two arrays - the original and the modified, and store the changes - in order to send a proper request for each one.

I will post Solution i finally came with

Firstly i decided to compare the strings of strigified arrays:


    const isIdentical = JSON.stringify(modifiedArr) === JSON.stringify(oldArr);
    if (isIdentical) {
      alert(`no changes`);
      return;
    }

Since - if arrays identical - there is no need to perform any request...

Removed

Next step i decided to collect removed array items (if were any):


const removed = oldArr.filter(({id}) => !modifiedArr.find(item => id === item.id));

Im only checking which items i cannot find in modified array.

Added

Collect the new items:


const added = modifiedArr.filter(({id}) => !oldArr.find(item => id === item.id));

Here im checking exactly the opposite - which items i cannot find in the old array

Modified

Collect the modified items


const modified = modifiedArr.filter(modifiedItem => !oldArr.find(item => JSON.stringify(modifiedItem) === JSON.stringify(item)))

Here im checking which items are different from old Array by checking their json strings.
Note: the in all the cases - i taking advantage of filter function of an Array.

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...