Home > Software design >  I want output as [1,2,2,3,5,6] but its giving [0,1,2,2,3,5,6]. I do not know why this 0 is coming in
I want output as [1,2,2,3,5,6] but its giving [0,1,2,2,3,5,6]. I do not know why this 0 is coming in

Time:09-17

I want output as [1,2,2,3,5,6] but its giving [0,1,2,2,3,5,6]. I do not know why this 0 is coming initially.

var merge = function(nums1, nums2, ) {
  var nums3 = nums1.concat(nums2);
  nums3.sort((a, b) => a - b)
  nums3.filter((currentValue, currentIndex) => {
    if (currentValue === 0)
      nums3.splice(currentIndex, 1)
  })
  nums1 = nums3
  return nums1
};
console.log(merge([1, 2, 3, 0, 0, 0], [2, 5, 6]))

CodePudding user response:

The following will return the merged result while filtering out all "falsy" values. You can make it more targeted by using .filter(v=>v!==0) instead of filter(v=>v):

function mergeNonZero(nums1, nums2)
{
  return nums1.concat(nums2)
   .filter(v=>v)
   .sort((a, b) => a - b);
};
console.log(mergeNonZero([1, 2, 3, 0, 0, 0], [2, 5, 6]))

CodePudding user response:

Update arr inside the filter function is a bad idea.

// let me explain a little bit:
const arr = ['1', '2', '3', 'zero 1', 'zero 2', 'zero 3'];
arr.filter((x, index) => {
    if (x.includes('zero')) {
        console.log('before', arr);
        console.log(`arr=${arr},index=${index}`);
        arr.splice(index, 1); // <== error here, u cant 
        console.log('after', arr);
        console.log('============================');
    }
});

console.log(arr);

try this:

const a = [1, 2, 4, 5, 2, 3, 5, 7, 0, 0];
const b = [2, 5, 6];
const c = [1, 2, 3, 0, 0, 0];

function mergeIgnoreZero(...params) {
    return params.flat().filter(num => num !== 0).sort((a, b) => a - b);
}

console.log(mergeIgnoreZero(a, b, c)); // [1,1,2,2,2,2,3,3,4,5,5,5,6,7]

CodePudding user response:

It's a little hard to tell what you're trying to do, but it looks like you're misusing .filter(). Normally the idea is that you pass a function to filter which returns true or false for whether you want to keep that element. The function you passed to filter,

(currentValue, currentIndex) =>
{ 
    if(currentValue === 0) 
    nums3.splice(currentIndex, 1) 
}

, doesn't return anything, because you've got the function body in {} and no return statement. On top of that for some reason you are modifying nums3 inside the filter function, which is... confusing.

  • Related