I have a table already populated with dataset from API. For demo, let just say I have 2 already added row on the table which I fetched from API. Now, I edited the second row also added another row. So what I want to achieve is that I want to get a new array of objects which have the the row I just edited along with the row I just added.
Following are the 2 arrays with dummy dataset I have.
First Array:
[ { id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 }, { id: '38sj3-23', user: { id: 21323 }, count: { start: 8, end: 36 }, point: 49 }, ]
Second Array:
[ { id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 }, { id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 }, { id: null, count: { start: 123, end: 2135 }, point: 323 }, ]
Notice that I edited the 2nd row values in the Second Array
. The third row in the 2nd array doesn’t have user id because the userId
will returned from server after posting it
Expected Output:
[ { id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 }, { id: null, count: { start: 123, end: 2135 }, point: 323 }, ]
I tried lodash
_.differencWith
/ _.intersectWith
but the output using that was like this below
[ { id: null, count: { start: 123, end: 2135 }, point: 323 }, ]
Only returned the newly added row on the table but ignored that I changed the values on the 2nd row as well.
NOTE: The table have only 3 columns where all of them are editable. coun: { start, end}
and point
Advertisement
Answer
You can use _.differenceWith
(https://lodash.com/docs/4.17.15#differenceWith)
const first=[ { id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 }, { id: '38sj3-23', user: { id: 21323 }, count: { start: 8, end: 36 }, point: 49 }, ] const second=[ { id: '38sj3-23', user: { id: 21323 }, count: { start: 12, end: 24 }, point: 56 }, { id: '38sj3-23', user: { id: 21323 }, count: { start: 36, end: 97 }, point: 15 }, { id: null, count: { start: 123, end: 2135 }, point: 323 }, ] let result=_.differenceWith(second, first, _.isEqual) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
_.differenceWith
:
This method is like _.difference
except that it accepts comparator which is invoked to compare elements of array to values. The order and references of result values are determined by the first array. The comparator is invoked with two arguments: (arrVal, othVal)
.