1

please ignore if this is a silly question to you. I just came up with my own solution to a problem, but I know its not a good solution and there are better smarter ways to do this, please answer if you have other solutions using javascript only.

Its asking to make a function to loop through an array of objects, and return the prop of the object if firstName matches the profile. Return some statements if firstName or prop provided to the function not found.

var contacts = [
        {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intruiging Cases", "Violin"]
    },
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    },
];
       
function lookUp(firstName, prop){

    for (var i = 0; i < contacts.length; i++){  
            var n = parseInt(contacts.length);

        
            if (contacts[i].firstName === firstName)    {
            
                if (contacts[i].hasOwnProperty(prop)){
                    return contacts[i][prop];
                }
                else return "No such property";
                }
            else if (i === (n-1)) {
                return "No such contact";
            }
    }
}

console.log(lookUp("Sherlock", "likes"));    

3

3 Answers 3

2
  • contacts.length is an integer, not a string, so parseInt is unnecessary.

  • You don't actually need the else if: you can just put it outside the loop, because if the contact exists, you would have exited the function already. This also makes n unnecessary, and the first point moot.

  • In general, it is a bad idea to return error messages, unless they are clearly distinguishable as error messages (see semipredicate problem); those should be thrown as exceptions, or at least returned as non-values null/undefined; or when you ask for lookUp('Adolf', 'favouriteSoup'), you might think the soup is called "No such contact". However, if the task you were given was to return the error message, I don't suppose there's anything you can do about it.

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

1 Comment

I agree. Raising exception is way better practice. If the property value is No such contact it would be very ridiculous and unable to differentiate between valid and invalid output.
0

you can change your loopUp method to this by using forEach

function lookUp(firstName, prop)
{
  var propValue = "No such contact";

  contacts.forEach( function( element ){ 
    if ( element.firstName == firstName ) 
    {
       propValue = element[ prop ] ? element[ prop ] : "No such property"; 
    }
  } );
  return propValue;
}

Also, just as @Amadan has mentioned rather than return error messages, throw an Error back which you will need to catch in the calling method.

try 
{
   lookUp();//making call here
}
catch(e)
{ 
   console.error( e );
}

Comments

0

I would suggest to split the two wanted functions to two functions.

  1. Get all objects with a given key/value pair lookUp(a, k, v)
  2. Get only one key from the array of object getKey(a, k)

function lookUp(a, k, v) {
    return a.filter(function (b) {
        return b[k] === v;
    });
}

function getKey(a, k) {
    return a.map(function (b ) {
        return k in b? b[k]: 'no property ' + k;
    });
}

function print(o) {
    document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}

var contacts = [{ "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intruiging Cases", "Violin"] }, { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] }];

print(lookUp(contacts, 'firstName', 'Sherlock'));
print(getKey(lookUp(contacts, 'firstName', 'Sherlock'), 'likes'));

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.