skip to Main Content

I’m new to JS. I’m trying to get the output from a function below with return but somehow it didn’t work and only console.log() works.

var merge = function(nums1, m, nums2, n) {
  let hasil = [];
  for (let i = 0; i <= m; i++) {
    const element = nums1[i];
    hasil.push(element);
  }
  for (let j = 0; j <= n; j++) {
    const element2 = nums2[j];
    hasil.push(element2);
  }
  let jawaban = hasil.sort();
  console.log(jawaban)
  return jawaban
};
merge([1, 2, 3], 1, [5, 9, 2], 2);

2

Answers


  1. Just try to call merge() function and assign the return value to a new variable. Then print it.

    var merge = function(nums1, m, nums2, n) {
      let hasil = [];
      for (let i = 0; i <= m; i++) {
        const element = nums1[i];
        hasil.push(element);
      }
      for (let j = 0; j <= n; j++) {
        const element2 = nums2[j];
        hasil.push(element2);
      }
      let jawaban = hasil.sort();
      return jawaban
    };
    let result = merge([1, 2, 3], 1, [5, 9, 2], 2);
    console.log(result);
    Login or Signup to reply.
  2. I think you can use Promise.

    var merge = function(nums1, m, nums2, n) {
     return new Promise(resolve => { 
       let hasil = [];
      for (let i = 0; i <= m; i++) {
        const element = nums1[i];
        hasil.push(element);
      }
      for (let j = 0; j <= n; j++) {
        const element2 = nums2[j];
        hasil.push(element2);
      }
      let jawaban = hasil.sort();
      resolve(jawaban);});
    }
    merge([1, 2, 3], 1, [5, 9, 2], 2).then(x=>console.log(x));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search