0

I would like to make a function like this work as intended in JavaScript:

function isLastElem(array, elem) {
    if (elem === array[array.length-1]) {
        return true;
    }
    else {
        return false;
    }
}

The intention is that the function should be able to identify the last element of any array. For example:

let arr = [0, 1, 2];
console.log(isLastElem(arr, 2)); // I would expect false to be returned
console.log(isLastElem(arr, arr[2])); // I would expect true to be returned

However, since numbers are primitive values, they are passed to the function by their values and thus both function calls return true. Any way to solve this and pass numbers by reference?

The important idea here would be to make it usable in a for each cycle. For example:

let arr = [0, 1, 0];
arr.forEach((elem) => {
    if (isLastElem(arr, elem)) {
        console.log("Found the last element!");
    }
});

At the first 0 the function should return false, since that is not the last element of the array. Then at the second 0 it should return true and log the message.

5
  • 4
    But ... 2 is in fact === to 2. All number values that are 2 are indistinguishable. Commented Dec 20, 2019 at 15:51
  • 1
    You'd have to compare the memory space entry, which is not possible in JavaScript. Commented Dec 20, 2019 at 15:53
  • And even for objects, your code only makes sense if you pass the actual array element value. Since you have to know an index to do that, it'd be much simpler to compare the index to the array length. Commented Dec 20, 2019 at 15:53
  • If you want to pass a "reference to an array element", pass the array and the index instead. In this case, coincidentally arr and 2. (It would make a better example to discuss if the array elements were not equal to the indices). Commented Dec 20, 2019 at 15:54
  • So, based on Rager's response, what I'm trying to do is pretty much impossible. Bummer, but thanks anyways! Commented Dec 20, 2019 at 16:14

4 Answers 4

1

You can do this by wrapping your number in an array or object, just like this:

let arr = [[0], [1], [2]];
console.log(isLastElem(arr, [2])); // returns false
console.log(isLastElem(arr, arr[2])); // returns true
Sign up to request clarification or add additional context in comments.

Comments

1

Even though I'm struggling to imagine why would anyone ever need to do that, I think we could make this work with Symbol:

Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

So this means we can use Symbol to stamp each element of an array. As you can see an array of 1s can be converted into an array of symbols of 1 which are all unique:

const xs = [1, 1];

xs[0] === xs[1];
//=> true

const ys = [Symbol(1), Symbol(1)];

ys[0] === ys[1];
//=> false

ys[0] === Symbol(1);
//=> false

ys[1] === ys[1];
//=> true

Therefore to identity the last element of an array, you actually need the reference to that element:

console.log(

  [1, 1, 1]
    // convert to list of symbols of 1
    .map(Symbol)
    // check if current element is equal to the last element
    .map((x, _, xs) => x === xs[xs.length - 1])
    
);
//=> [false, false, true]


Of course the problem is that it wraps each element inside a box from which it can't escape.

We can put each element inside an object, hidden behind a "secret unique" key. Each object has a method to extract its value and compare itself with other similar objects:

const obj = (k, v) => (
  { [k]: v
  , get: () => v
  , equals: o => o[k] === v
  });

const stamp = (arr, secret = Date.now()) =>
  arr.map((x, i) => obj(`${secret}@@${i}`, x));
  
const arr = stamp([1, 1, 1]);

arr.forEach((x, _, xs) => {
  console.log(x.get(), x.equals(xs[xs.length - 1]));
});

Comments

0

You could maybe not store the native number, but an instance of Number..

eg.

function isLastElem(array, elem) {
    if (elem === array[array.length-1]) {
        return true;
    }
    else {
        return false;
    }
}

let arr = [new Number(0), new Number(1), new Number(2)];

console.log(isLastElem(arr, 2)); // I would expect false to be returned
console.log(isLastElem(arr, arr[2])); // I would expect true to be returned

3 Comments

Yeah, that would be a solution, but using new Number is in general a very bad practice.
I'm afraid that is quite impossible in my current project :( Thanks for the answer though.
@Bergi Yeah, not something I would do personally. But was just answering the OP's question. Specifically -> Any way to solve this and pass numbers by reference?
-1

You can try this code


let arr = [0, 1, 2];
console.log(isPrimitive(arr[index+1]));

function isPrimitive(val) {
  return isString(val) || isBoolean(val) || (isNumber(val) && !isNaN(val));
}

2 Comments

What does this have to do with the question?
@Pointy To check the array index => for example isPrimitive(index + 1)

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.