I need condition to be true only if all properties of the object (variables) are not equal to each other. How can I condition object properties' inequality in a more optimal way? If the number of them grows the combination of obj[1]!=obj[2]
and so on will grow enormously
var obj = {
1: linksArray[randomNumber],
2: linksArray[randomNumber2],
3: linksArray[randomNumber3]
}
if(obj[1]!=obj[2] && obj[1]!=obj[3] &&
obj[2]!=obj[3] && obj[2]!=obj[1] &&
obj[3]!=obj[2] && obj[3]!=obj[1]
) {
arr.push(linksArray[randomNumber]);
arr.push(linksArray[randomNumber2]);
arr.push(linksArray[randomNumber3]);
break;
}
CodePudding user response:
Get the object's values, and create a Set. If the Set's size is identical to the values length, all values are unique:
const allUnique = obj => {
const values = Object.values(obj)
return new Set(values).size === values.length
}
const obj1 = { 1: 'a', '2': 'b', 3: 'c' }
const obj2 = { 1: 'a', '2': 'b', 3: 'c', 4: 'b' }
console.log(allUnique(obj1)) // true
console.log(allUnique(obj2)) // false
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Put all the values in an array
, then use it to build a Set
(data structure where all items are different, documentation).
If the array has the same amount of items as the set, you're sure they're all different.
var obj1 = {
field1: true,
fiedl2: 2,
field3: "red",
}
var obj2 = {
field1: true,
fiedl2: 2,
field3: "red",
field4: 2
}
function allDifferent(obj) {
const values = Object.values(obj);
return new Set(values).size === values.length
}
console.log(allDifferent(obj1));
console.log(allDifferent(obj2));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Check for duplicates by making a Set of all the object values - these will be unique. Then compare the size of the Set to the number of key/values in the original object. If they are different - there is a duplicate in the original. If they are the same, the values of the original are unique.
const uniqueValues = new Set(Object.keys(obj));
if (uniqueValues.size == obj.length) {...do stuff}
CodePudding user response:
Check out this guy: https://medium.com/@weberzt/finding-duplicate-integers-in-an-array-in-javascript-4fa9f0f3c45
Very interesting solution. In this solution the a type is an array.
function containsDuplicates(a) {
return (new Set(a)).size !== a.length;
}
Complexity is O(n) which is not bad