skip to Main Content

I am trying to solve this challenge.

Question

Given are two arrays a and b, both have three elements. Return a new array of length 2 containing both middle (index 1) elements of the arrays).

Error
Uncaught ReferenceError: a is not defined on line: 10 First Try
Second Try

First try

function goldenMiddle(a, b) {
a = [4,6,2];  // assign an array to a and b 
a = [1,6,8];
var c = []; // created a new array
var resultA = a[1];   // index 1 of array a
var resultB = a[1];  // index 1 of array b 
var newResult = c.push(resultA) + c.push(resultB); // push the resultA and resultB to c
return c;  // return c
}
goldenMiddle()

Second Try

function goldenMiddle(a, b) {
a = []; 
a = [];
var c = []; // created a new array
var resultA = a[1];   // index 1 of array a
var resultB = a[1];  // index 1 of array b 
var newResult = c.push(resultA) + c.push(resultB); // push the resultA and resultB to c
return c;  // return c
}
goldenMiddle(a[1,6,8],  b[4,6,2])

Any idea what the problem might be?

Thanks

2

Answers


  1. For your error, you must call goldenMiddle like this

    function goldenMiddle(a, b) {
      a = []; 
      a = [];
      var c = []; // created a new array
      var resultA = a[1];   // index 1 of array a
      var resultB = a[1];  // index 1 of array b 
      var newResult = c.push(resultA) + c.push(resultB); // push the resultA and resultB to c
      return c;  // return c
    }
    goldenMiddle([1,6,8],  [4,6,2]) // remove the a and b from this line
    

    However, to accomplish your function, there are a couple other things you need to adjust

    function goldenMiddle(a, b) {
      // a = []; Comment these lines, if you don't a will be set to an empty array
      // a = [];
      var c = []; // created a new array
      var resultA = a[1];   // index 1 of array a
      var resultB = b[1];  // index 1 of array b (change from 'a' to 'b')
      c.push(resultA); // These need to be independent
      c.push(resultB); // push the resultA and resultB to c
      return c;  // return c
    }
    console.log(goldenMiddle([1,6,8],  [4,6,2])) // remove the a and b from this line and print it
    
    Login or Signup to reply.
  2. In both tries, you’re only using the parameter a and not b.

    By using a = [], you are clearing the array.

    Also, Arrays are directly passed as parameters simply just using [].

    Your code can be simply like this:

    function goldenMiddle(a, b) {
        return [a[1], b[1]];
    }
    
    goldenMiddle([1, 6, 8], [4, 6, 2]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search