0

I tried using concat but unable to get array like [1,2,66]. By using push I got. But using concat is it possible or what is the reason I am not getting the result.

const arr = [1, 2, 66];
const data = arr.reduce((obj, k) => { 
            obj.concat(k); 
            return obj 
},[]);
console.log(data);
3
  • concat returns a new array. It doesn't mutate the current one. So: return obj.concat(k). Commented Oct 8, 2019 at 9:58
  • Thanks got solution. But I need clarification what is the difference I used like return obj and u used return obj.concat(k) Commented Oct 8, 2019 at 10:04
  • 1
    great for the answer Commented Oct 8, 2019 at 10:09

1 Answer 1

1

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

So, obj.concat(k) doesn't do anything, and you're returning an unchanged obj in the next line.

To solve this you can assign the concat to a new variable and return that...

const newObj = obj.concat(k);
return newObj;

... or simply return the result of the concat:

return obj.concat(k);

const arr = [1, 2, 66];

const data = arr.reduce((obj, k) => {
  return obj.concat(k);
}, []);

console.log(data);

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

1 Comment

Speaking of simply: (obj,k) => obj.concat(k) is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.