-2
parm1 = "val1"
parm2 = "val1"
parm3 = "val2"
parm4 = "val1"

How can I check if a value was assigned more than 2 times for a list of parms (the value can be any and is unknown)

-later edit-

I've also found this solution

const parm1 = "val1",
  parm2 = "val1",
  parm3 = "val2",
  parm4 = "val1";

const parms = [parm1,parm2,parm3,parm4];
const list = [...new Set(parms)];
if(list.length >= 3){
  console.log("more than 3 different values")
}
Andrei
  • 1
  • 1
  • 3
    Where and how these variables are actually getting their values? If you hardcode the values like this, the question is not worth of asking. – Teemu Jul 13 '20 at 15:12
  • 3
    What are you trying to accomplish, exactly? – chazsolo Jul 13 '20 at 15:14
  • 2
    can you share your code? – Sven.hig Jul 13 '20 at 15:15
  • the values are not hardcoded and are assigned by the user. there are around 1000 possible values. More exactly the user will have on UI multiple select inputs and I want to check if he selected more than 3 different values for all the select input. I only want to ask the user to select less than 3 different value for each select input ( used here as parm1, parm2, parm3, parm4) – Andrei Jul 13 '20 at 16:36
  • @Andrei, I've added another answer below based on your comment clarifying. Please let me know if this (or the previous attempt) is useful. (I'm still not entirely clear on what you're looking for) – phhu Jul 13 '20 at 23:17
  • I'd suggest you to store the values in a data structure, use an array or object instead of separate variables. – Teemu Jul 14 '20 at 16:37

2 Answers2

0

Something like this? You can put the parms in an array, filter the array by the value, and then use the length of the filtered array:

const parm1 = "val1",
  parm2 = "val1",
  parm3 = "val2",
  parm4 = "val1";

const parms = [parm1,parm2,parm3,parm4];

const countInArray = (arr,val) => arr.filter(x=>x===val).length;
console.log(countInArray(parms,"val1"));
// 3

If you're checking lots of values, a specific function might be useful:

const countInArrayGreaterThan = (arr,count,val) => 
  arr.filter(x=>x===val).length > count;
console.log(countInArrayGreaterThan(parms, 2, "val1"));
// true
phhu
  • 1,462
  • 13
  • 33
0

...from your comment, perhaps you mean that you want to check if there are more than two distinct values choose across all the parms / inputs. In this case, you could use a unique function on an array of the parms, based on the methods at Get all unique values in a JavaScript array (remove duplicates) .

E.g. in ES5, something like this:

var parm1 = "val1", parm2 = "val1", parm3 = "val2", parm4 = "val1";
var parms = [parm1,parm2,parm3,parm4];

function onlyUnique(value, index, self) {return self.indexOf(value) === index;}

var uniqueParms = parms.filter(onlyUnique)
var hasMoreThanTwoDistinctParmValues = uniqueParms.length > 2;
// = false
phhu
  • 1,462
  • 13
  • 33