0

Is there a way to shorten or refactor this longVersion() function below? Any ideas is appreciated. Thanks!

https://replit.com/talk/share/convert-obj-to-ary/137799

const person = {
  name: 'Juan De la Cruz',
  job: 'Programmer',
}

function longVersion(person) {
  let aryPerson = []
  if (Array.isArray(person) && person.length > 0) {
    aryPerson = person
  } else {
    aryPerson.push(person)
  }
  return aryPerson
}

const result = longVersion(person)
console.log('longVersion:', result)

//output: longVersion: [ { name: 'Juan De la Cruz', job: 'Programmer' } ]
3
  • So, if your input is an object, you want an array containing that object out, and if it's an array, you want just that array out? Commented Apr 28, 2021 at 10:42
  • 2
    Pretty sure this belongs on codereview.stackexchange.com Commented Apr 28, 2021 at 10:49
  • Thanks for sharing the links sir. Commented Apr 28, 2021 at 10:52

1 Answer 1

2

If all you want to do is convert the input to an array, if it isn't already an array, then this is enough:

const person = { name: 'Juan De la Cruz', job: 'Programmer' };

function toArray(person) {
  return Array.isArray(person) ? person : [person];
}

const result = toArray(person);
console.log('toArray:', result);

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

1 Comment

Hmm, this is nice. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.