I've spent a couple hours to compare of two object in array, but i'm not find a way to achieve it
Let say i've these array called compareWith
:
[{a:1},{b:2},{c:3}]
and this is an array to be compared and the expected result:
[{b:2}]
true -> because {b:2} is in compareWith
[{c:3},{a:1}]
true -> because {c:3} and {a:1} is in compareWith
[{a:1},{b:2}]
true -> because {a:1} and {b:2} is in compareWith
[{a:1},{d:3}]
false -> because {d:3} is not in compareWith
even {a:1} is in compareWith
how can i achieve the above result using javascript function/ lodash?
EDIT:
just tried this but i want a boolean
as a result:
import _ from 'lodash';
var a = [{a:1},{b:2},{c:3}]
var b = [{c:3},{a:1}]
let result = _.differenceWith(a, b, _.isEqual)
console.log(JSON.stringify(result)) //[{b:2}]
You can do it like this
function compareWith(originalArray, arrayToCompareWith){
for(let obj of originalArray)
if(!arrayToCompareWith.find((x)=>_.isEqual(x, obj)))
return false;
return true;
}
or just in one line using lodash as follows
var main = [{a:1},{b:2},{c:3}], a1=[{b:2}], a2=[{c:3},{a:1}], a3=[{a:1},{b:2}], a4=[{a:1},{d:3}]; function compareWith(originalArray, arrayToCompareWith){ return _.differenceWith(arrayToCompareWith, originalArray, _.isEqual).length == 0; } console.log(compareWith(main, a1)); console.log(compareWith(main, a2)); console.log(compareWith(main, a3)); console.log(compareWith(main, a4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
You could use filter
vanilla javascript
main = [{a:1},{b:2},{c:3}] a1=[{b:2}] a3=[{c:3},{a:1}] a4=[{a:1},{b:2}] a5=[{a:1},{d:3}] function check(main,a){ res =main.filter(o=>a.some(e=>Object.keys(e)[0]==Object.keys(o)[0] && Object.values(e)[0]==Object.values(o)[0])) return res.length==a.length? true: false } console.log(check(main,a1)) console.log(check(main,a3)) console.log(check(main,a4)) console.log(check(main,a5))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.