Let’s write a function compareRobots, that takes 2 robots and returns true, if only all the characteristics of both are the same. (the order is not important, only the keys and values).
Notes:
each robot has its own unique serialNo (do not check it when comparing)
properties can’t have values of undefined and NaN.
const charlie = { serialNo: 1, chipVer: 12 };
const lordy = { serialNo: 2, chipVer: 12 };
compareRobots(charlie, lordy); // true
const paul = { serialNo: 3, chipVer: 15 };
compareRobots(paul, charlie); // false
const mike = { serialNo: 4, chipVer: 12, wheels: 1 };
compareRobots(mike, charlie); // false
const max = { serialNo: 5, engineVer: 12 };
compareRobots(max, charlie); // false
const steve = { serialNo: 6 };
compareRobots(steve, charlie); // false`
I write a code but I don’t know how to ignore the serialNo of robots
const compareRobots = (robot1, robot2) => {
// write code here
const entries1 = Object.entries(robot1);
const entries2 = Object.entries(robot2);
if (entries1.length !== entries2.length) {
return false;
};
for (let i = 0; i < entries1.length; i++) {
if (entries1[i][0] !== entries2[i][0]) {
return false;
}
if (entries1[i][1] !== entries2[i][1]) {
return false;
}
};
return true;
};`
>Solution :
Using Object.keys() and a Set() to get all unique keys of the two objects, then I simply remove the ones I don’t want to compare ("serialNo"
)
function compareRobots(a, b) {
// determine all unique keys
const keys = new Set([].concat(Object.keys(a), Object.keys(b)));
// ignore serialNo;
keys.delete("serialNo");
for (const k of keys)
if (a[k] !== b[k]) return false;
return true;
}
const charlie = { serialNo: 1, chipVer: 12 };
const lordy = { serialNo: 2, chipVer: 12 };
const paul = { serialNo: 3, chipVer: 15 };
const mike = { serialNo: 4, chipVer: 12, wheels: 1 };
const max = { serialNo: 5, engineVer: 12 };
const steve = { serialNo: 6 };
console.log({
"charlie, lordy": compareRobots(charlie, lordy), // true
"paul, charlie": compareRobots(paul, charlie), // false
"mike, charlie": compareRobots(mike, charlie), // false
"max, charlie": compareRobots(max, charlie), // false
"steve, charlie": compareRobots(steve, charlie), // false`
});