0

I have an array that contains some of these 3 values: ['daily', 'monthly', 'yearly']

but sometimes the array only contains: ['monthly', 'daily']

and what I want is to get the minimum between these 3 values which is daily and if not there I want monthly and also if it's not there I want the yearly. How can I achieve that ?

3
  • 1
    if (array.includes('daily')) { /* DAILY */ } else if (array.includes('monthly')) { /* MONTHLY */ } else { /* YEARLY */ } Commented May 8, 2022 at 10:35
  • Please add the code you've attempted to your question as a minimal reproducible example. Commented May 8, 2022 at 10:36
  • 1
    Sorry but cannot get what you mean. Please show the examples. Commented May 8, 2022 at 10:41

4 Answers 4

1

You can approach this issue by comparing the values daily, monthly, and yearly alphabetically/by ASCII order

Sign up to request clarification or add additional context in comments.

3 Comments

nicely spotted, I didn't even think about this approach. Could you please add a code example in your answer?
By using string1.localeCompare(string2): returns -1 if smaller, 1 if bigger, and 0 if equal. use it while iterating through the array. If your array could contain only those 3 values, just use : array.includes('daily')
Ok, I was thinking about alphabetical ascending sort of the array, then smaller value will be array[0]
1

Simplest approach that doesn't rely on alphabetic ordering (and would therefore still work when adding new intervals like hourly):

function getLowest (arr) {
  const order = ['daily', 'monthly', 'yearly'] 
  return order.find(val => arr.includes(val))
}

This works because find will return the first matching result.

Comments

0

Here's a simple one-liner function:

const arr1 = ['daily', 'monthly', 'yearly'], arr2 = ['monthly', 'yearly'], arr3 = ['yearly'], [d,m,y] = arr1;
const lowestVal = (arr) => arr.find(x => x===d) ?? arr.find(x => x===m) ?? y;

console.log(lowestVal(arr1));
console.log(lowestVal(arr2));
console.log(lowestVal(arr3));

Comments

0

Here is the function you just need to pass your array it will return a minimum value.

function getMinimum(arr)
{
    return arr.includes('daily') ? 'daily' : arr.includes('monthly') ? 'monthly' : arr.includes('yearly') ? 'yearly' : "";
}
var arr1 = ['daily', 'monthly', 'yearly'];
console.log(getMinimum(arr1));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.