0

Is it possible to design a function that has an array like the below and use an if statement to check if the type is equal to the following in any of my categories in my array below and return its associate category code?

Example:

function CheckCategory(type) {

array = 

[NOTES, CAT-A],
[BOOKS, CAT-B],
[MUSIC, CAT-C],
[SOFTWARE, CAT-D]

if (type == "NOTES") { return "CAT-A" }


}

3 Answers 3

1

What about

var CatTable={"NOTES": "CAT-A", "BOOKS": "CAT-B", "MUSIC": "CAT-C", "SOFTWARE": "CAT-D"};

function  CheckCategory(type) {
  if (CatTable[type]) return CatTable[type];
  else return "UNKNOWN CATEGORY"
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why is CatTable global (or at least outside of CheckCategory)?
I assumed, it might also be needed elswhere
0

You could declare your array variable as a two-dimensional array (an array of arrays):

function checkCategory(type) {
    var array = [
        ['NOTES', 'CAT-A'],
        ['BOOKS', 'CAT-B'],
        ['MUSIC', 'CAT-C'],
        ['SOFTWARE', 'CAT-D']
    ];

    // Then, simply loop over your array and check for the type
    for (var i = 0; i < array.length; i++) {

        if (type == array[i][0]) {

            // It will return the CAT-X of the matching type
            return array[i][1];
        }
    }
}

Also, you could declare your variable as an object, and return the value of type property:

function checkCategory(type) {
    var values = {
        NOTES: 'CAT-A',
        BOOKS: 'CAT-B',
        MUSIC: 'CAT-C',
        SOFTWARE: 'CAT-D'
    }

    return values[type];
}

Comments

0
function CheckCategory(type) {
    var data = [
        ['NOTES', 'CAT-A'],
        ['BOOKS', 'CAT-B'],
        ['MUSIC', 'CAT-C'],
        ['SOFTWARE', 'CAT-D']
    ];

    for( i = 0; i < data.length; i++) {
        if (data[i][0] == type) {
            return data[i][1];   
        }
    }

    return "Not found";
}

http://jsfiddle.net/Mansfield/5s8wr/2/

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.