skip to Main Content

could you see where I would add code to display -1 if knife or fork is not present in the array?

This is the question I am trying to solve – The function’s return value should be an object with two properties, knife and fork, which contain the index positions of the knife and fork from the input array. If either the knife and/or fork are not present in the input array, that property’s value should be -1.

    function findKnifeAndFork(utensils) {
    console.log(utensils)
    let knife = 0;
    let fork = 0;
    let obj ={};

    for(let i = 0; i<utensils.length; i++){
         if(utensils[i] === 'knife'){
            knife = i
            obj.knife=knife    
    };

    for(let i = 0; i<utensils.length; i++){
    if(utensils[i] === 'fork'){
    fork = i
    obj.fork=fork    
    }
    
    } 
    }   return obj
    }

I have added it within each for loop as an else and outside both loops as a standalone for loop and neither are working. ( the below is currently working to display the index code of knife and fork – when they are both present in the array)

3

Answers


  1. A common pattern is to initialize the variable with the "not found" value and then update it once the condition matches:

    obj.knife = -1
    for(let i = 0; i<utensils.length; i++){
         if(utensils[i] === 'knife'){
            obj.knife=i
            break // ???    
    }
    

    Note that you don’t need an intermediate variable here. Whether to break or not, depends on which index you want to return if there are multiple knives.

    Login or Signup to reply.
  2. Your code looks fine, except that you need to initially set knife and fork to -1 in obj to cover the case when either is not found in the array.

    The indexOf method already returns -1 if no match is found, and so you can achieve your goal with a one-liner like this:

    function findKnifeAndFork(utensils) {
      return {knife: utensils.indexOf('knife'), fork: utensils.indexOf('fork')}
    }

    To avoid some repetition, you can also do:

    function findKnifeAndFork(utensils) {
      return Object.fromEntries(['knife', 'fork'].map(k => [k, utensils.indexOf(k)]))
    }
    Login or Signup to reply.
  3. indexOf is purpose-built for this sort of thing. You can simplify quite a bit if you use it… and avoid looping.

    function findKnifeAndFork(utensils) {
      return {
        "fork": utensils.indexOf("fork"),
        "knife": utensils.indexOf("knife")
      }
    }
    
    let onlyFork = ["fork", "spoon", "ladle", "hammer"];
    console.log(findKnifeAndFork(onlyFork));
    
    let onlyKnife = ["screwdriver", "spoon", "knife", "hammer"];
    console.log(findKnifeAndFork(onlyKnife));
    
    let forkAndKnife = ["screwdriver", "spoon", "knife", "hammer", "fork"];
    console.log(findKnifeAndFork(forkAndKnife));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search