1

i wrote the following code .is there any one liner for the following ?

if (this.selectedUsersToAdd.length) {
  this.selectedUsersToAdd.push(selectedUsersToAdd);
} else {
  this.selectedUsersToAdd = selectedUsersToAdd;
}
1
  • What is the benefit to a one liner? Commented May 18, 2018 at 16:16

2 Answers 2

2

You can use ternary operator and assign value of array you want to add if first one is empty or result of concat if it's not empty.

let arr = [];
let add = [1, 2];
arr = arr.length ? arr.concat(add) : add;

console.log(arr)

In case you want to push whole new array to old one if old one is not empty, then first push new one and return old one.

let arr = [1];
let add = [1, 2];
arr = arr.length ? (arr.push(add), arr) : add;

console.log(arr)

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

Comments

1

Using a ternary:

this.selectedUsersToAdd.length ? this.selectedUsersToAdd.push(selectedUsersToAdd) : this.selectedUsersToAdd = selectedUsersToAdd

Comments

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.