warCommander
warCommander

Reputation: 449

Search multiple times in array in Javascript

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 ?

Upvotes: 0

Views: 173

Answers (4)

Mateen
Mateen

Reputation: 531

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));

Upvotes: 0

CherryDT
CherryDT

Reputation: 29092

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.

Upvotes: 1

connexo
connexo

Reputation: 56853

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));

Upvotes: 0

Taher ben abdallah
Taher ben abdallah

Reputation: 71

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

Upvotes: 1

Related Questions