Home > Software engineering >  How to write a custom function that has the same behavior of inbuilt Array Join in Node.js
How to write a custom function that has the same behavior of inbuilt Array Join in Node.js

Time:04-24

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

CodePudding user response:

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-!" 

CodePudding user response:

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", "!"],"-"));

CodePudding user response:

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","!"]);

CodePudding user response:

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

CodePudding user response:

  1. You should probably return your joined string from the function and then log the result.

  2. Maybe also pass in a delimeter argument so you don't just have to use "-"; you can use anything. And that will mirror the join method a lot better.

  3. Most importantly: check that the current index is less than the length of the array (-1). If it is add the delimeter. If it the equal to length - 1 don't add it.

function join(arr, delimeter) {
  let str = '';
  for (let i = 0; i < arr.length; i  ) {
    if (i < arr.length - 1) {
      str  = arr[i]   delimeter;
    } else {
      str  = arr[i];
    }
  }
  return str;
}

console.log(join(['Hello', 'World', '!'], '-'));
console.log(join(['We', 'Have', 'Popcorn', '!'], '           
  • Related