1

Is there a shorter way of doing this:

let arrSlicePush = arr.slice();
arrSlicePush.push(num);
let x = func(arrSlicePush);

Thanks in advance.

3
  • Did you mean let ArrSlicePush = Arr.slice(); ArrSlicePush.push(Num); let x = Func(ArrSlicePush); ? Commented Oct 2, 2020 at 13:28
  • Yes, I jus write it shorter Commented Oct 2, 2020 at 13:30
  • .push() returns number of elements pushed+original length of array. So, you made a mistake. You didn't write it shorter. Commented Oct 2, 2020 at 13:32

3 Answers 3

7

Simply do:

func([...arr, num]);

Worth noting that Array.push returns the length of the array anyway, so the first example is irrelevant.

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

Comments

2

You would call Array.prototype.concat instead of Array.prototype.push.

Also, since concat already merges two arrays and returns a new one, you so not even need to slice the original array.

const arr = [ 0, 1, 2, 3, 4 ];
const num = 5;

const func = (arr) => arr.map(e => String.fromCharCode(e + 65));

const x = func(arr.concat(num));

console.log(x);


Notes

[ ...arr, val ] is syntactic sugar for arr.concat(val)

Comments

0

This works:

func(animals.slice().concat(num));

2 Comments

See this answer, you don't need to use .slice() ;)
yeah, you are totaly right, but the question was to use both slice() & puch(), since push() cant not be used so I suggested the concat().... but we dont know if the person need to use slice() method for other reasons (slice(2), slice(2,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.