Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
How to write a custom function that has the same behavior of inbuilt Array Join in Node.js

function arr(a) {
  let sum = "";
  for (let i = 0; i < a.length; i++) {
    sum += a[i] + "-";
  }
  console.log(sum);
}

arr(["Hello", "World", "!"]);

It's printing "-" after "!" as well

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Just use ternary operator to determine rendering last dash

function arr(a){
  let sum= "";
  for(let i=0; i<a.length; i++){
    i === a.length-1 ? sum+=a[i] : sum+= a[i]+"-";
  }
  console.log(sum);
}
arr(["Hello","World","!"]);

about 4 years ago · Santiago Trujillo Report

0

I think you only need to add one condition for the last item. For example

function arr(a){
  let sum= "";
  for(let i=0; i<a.length; i++){
      sum+= a[i] + ((i<a.length-1) ? "-" : "");
  }
  return sum
}
const result = arr(["Hello","World","!"]);

console.log(result)

Or it's neater with array reduce

const join = (arr, separator) => {
  return arr.reduce((prev, current)=> prev + separator +  current)
}

const rs =join(["Hello", "World", "!"], "-")
console.log(rs)

Same result

"Hello-World-!" 
about 4 years ago · Santiago Trujillo Report

0

you can do this as follow

function arr(a,glue='') {
  let sum = "";
  let i=0;
  for (i = 0; i < a.length-1; i++) {
    sum += a[i] + glue;
  }
  sum+=a[i];
 return sum;
}

console.log(arr(["Hello", "World", "!"],"-"));

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!