0

I want return an array as a string in my function.
Example:

return [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

should be returned as "[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]" which is a string. I don't want to use .join() because it removes the [] brackets.

8
  • I'm voting to close this question as off-topic because it is too general to the language of programming; specifically JavaScript. Flooding SO with simple questions — that are clearly defined in the language or showcased in most books — should be avoided. Commented Aug 6, 2017 at 13:06
  • 1
    Do you mean SO is for experienced programmers only? From Where should I get help? Please be nice. Commented Aug 6, 2017 at 13:35
  • Not at all. There really is no dumb question, but SO should expect someone to make an effort to learn a concept via some resource / material and come here with questions when they can't grasp what it is they are learning or attempting to do. The Q&A forum isn't intended to replace existing documentation, but more to support the learning process. Commented Aug 6, 2017 at 13:40
  • I have heard you but please look at my question and try to answer from the documentation. All they gave me was .join() as I have indicated above. I wish you would be helping solving problems instead of closing them simply because they aren't a problem to you. Commented Aug 6, 2017 at 13:43
  • 1
    @NisargShah Meta is unnecessary. When I voted to close, I chose for "other", which required a reason. The reason posts as a comment here. The OP had follow-up, which I addressed. I think it's run its course. It wasn't personal and I don't think he took it that way. Simple questions are discouraged for many reasons; e.g., point-farming, landing page inflation, etc. Whether SO wants to be more proactive is up to the community and admins. My vote is only one (and it'd take 5 to close) - if 4 others don't feel the same, everything is as it should be :) Commented Aug 6, 2017 at 16:52

2 Answers 2

5

You can use JSON.stringify - it converts JS objects into JSON strings.

console.log(JSON.stringify([[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]));

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

3 Comments

I want to return it in a function. I don't want to use console.log
@Hoslack then return it
JSON,stringify is itself a function, so you won't need to wrap it inside another function.
1

Return your array after JSON.stringify it. like that:

var arr = [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]];
return JSON.stringify(arr);

It will convert the array object into string.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.