2

I'm working on a function that takes two arrays of numbers as its arguments. I use a ternary operator to determine if both arrays are of the same length or not. If not, I run an if condition loop to determine which is longer and set the name of the argument as the property of a variable named longer so I can access the element with the most items without knowing which it is beforehand. Here's a sample.

someFunc(numListA, numListB){
    let isEqual = (numListA.length == numListB.length) ? true : false;

    let longer     = '',
        shorter    = '',
        difference = [longer].length - [shorter].length,
        appendNums = [];

    if(!isEqual){
        if(numListA.length > numListB.length){
            longer = 'numListA'; shorter = 'numListB';
        }
        else{ longer = 'numListB'; shorter = 'numListA'; }

        appendNums = [...[longer].splice([longer].length-difference-1, [longer].length)];
    }
    ........
}

When console.log()ing the appendNums variable it returns the text in the longer variable as a string rather than plugging the variable in place as something I can access.

What I want this part of the function to do is to determine the difference in the length between the two arrays and take the trailing entries of, whichever, the longest and store them in the appendNums variable. The only thing I could think to do was trying backticks instead of quotes to make them template literals but it still had the same result. How can I get the bracket notation to plug in the variable name so it can be accessed?

4
  • 1
    longer = 'numListA' should be longer = numListA same applicable for shorter also Commented Aug 23, 2018 at 6:00
  • I haven't completely understood the code yet but I think you have used [longer].length even before you have determined longer (at this point, longer & shorter both are empty strings.) Commented Aug 23, 2018 at 6:01
  • "How can I get the bracket notation to plug in the variable name so it can be accessed?" In the given situation, you cannot directly use the text version of that variable name to access the value. Commented Aug 23, 2018 at 6:03
  • You seem to think that the notation [variableName] will return whatever isassigned to variable whose name is stored in variableName. This is not true though: e.g. [longer] in the 7th line evaluates to the singleton array [''] instead of the array assigned to the variable whose name matches the value of longer . Generally, you cannot access the scope of a function reflectively without using eval. There is no need to do that either if you follow the suggestion by @JavascriptLover-SKT . Commented Aug 23, 2018 at 6:27

3 Answers 3

2

First of all, this code

difference = [longer].length - [shorter].length

will always be 0, because you are accessing the property .length on a newly-created array which contains exactly one element - longer or shorter (which might also be an array, but it is just an item in the new array and plays no role in the parent array's length).

I think you are over-thinking the problem by trying to access the arrays by using the variables' names using computed properties. You already have both arrays in variables, readily accessible, and you know exactly which two variables you will be comparing so it makes no sense to use a computed property access even if you could use it.

The most simple algorithm to do what you are trying to achieve would look something like this:

  1. A function receives two arguments - two arrays to compare
  2. Determine which array is longer and save it in a new variable
  3. Slice the longer array, starting at the index equaling the last index in the shorter array and running to the end of the longer array (thus creating a shallow copy of all the trailing items in the longer array)
  4. Do what you want with the slice. You now have all the trailing items in a new array.

As you can see, you do not need any crazy syntax or tricks to do that. Here is a reference implementation of that algorithm:

function getTrailingItems(first, second) {
  if (first.length === second.length) {
    // They are equal -> no trailing items exist
    return []
  }

  // Determine which array of the two is longer and which one is shorter.
  // We will use this to make the final slice.
  const longer = first.length > second.length
    ? first
    : second
  const shorter = first.length > second.length
    ? second
    : first

  // Create a shallow copy of all the extra elements at the end of the longer array.
  return longer.slice(shorter.length)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of relying on variable name, use the actual variable. [] syntax is computed property syntax which only works for object properties.

if(numListA.length > numListB.length){
    longer = numListA; shorter = numListB;
}
else{
    longer = numListB; shorter = numListA;
}

appendNums = [...longer.splice(longer.length-difference-1, longer.length)];

If you want to depend on variable name, you can use eval to evaluate the string variable, but it wont be recommended.

appendNums = [...eval(longer).splice(eval(longer).length-difference-1, eval(longer).length)];

1 Comment

There are various valid usecases for eval, accessing a variable that way is definitely one of the worst no go. It will most likely break linter, minifier, composer, transpilers, ...
1

var numListA = [1, 2, 3, 4, 5];
var numListB = [12, 14, 15, 16, 18, 20];

function execFunc() {
  someFunc(numListA, numListB);
}

function someFunc(numListA, numListB) {
  let isEqual = (numListA.length == numListB.length) ? true : false;

  let longer = '',
    shorter = '',
    difference = longer.length - shorter.length,
    appendNums = [];

  if (!isEqual) {
    if (numListA.length > numListB.length) {
      longer = numListA;
      shorter = numListB;
    } else {
      longer = numListB;
      shorter = numListA;
    }

    appendNums = [[...longer].splice([...longer].length - difference - 1, [...longer].length)];
  }
  console.log(appendNums);
}
<button onclick="execFunc()">Click me</button>

1 Comment

You should not create code only answers without any explanation what you have changed and why. The OP or any otjher person having that problem wouldn't have tried to use [] if it would have been clear to them that they just could have used an assignment of the actual object.

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.