4

I am confused on how to convert a nested array into a string but there is still array inside a string, can somebody help me?

input : [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]

expected output :

"Jimmy,30,[Ford,BMW,Fiat]
   Fiona,25,[Ford,BMW,Fiat]
   Anny,19,[Ford,BMW,Fiat]
   Gabby,27,[Ford,BMW,Fiat]
   Kevin,20,[Ford,BMW,Fiat]"

thank you

2
  • when you are looping through outer array, check if individual item is an array - Array.isArray() - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 16, 2018 at 17:57
  • 2
    JSON.stringify provides an output that comes very close. Commented Jan 16, 2018 at 18:06

7 Answers 7

3

We can just use a recursive function to store anything and everything within any array in a string and then return the string from the function.

function printArr(arr) {
let str = "";
  for (let item of arr) {
    if (Array.isArray(item)) str += printArr(item);
    else str += item + ", ";
  }
  return str;
}

console.log( 
printArr([
  ["Jimmy", 30, ["Ford", "BMW", "Fiat"]],
  ["Fiona", 25, ["Ford", "BMW", "Fiat"]],
  ["Anny", 19, ["Ford", "BMW", "Fiat"]],
  ["Gabby", 27, ["Ford", "BMW", "Fiat"]],
  ["Kevin", 20, ["Ford", "BMW", "Fiat"]]
]) 
);

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

6 Comments

You should replace " " with "," and printArr(item) needs to be surounded by [ ... ]
@JonasW. I realized the " " to "," right after I posted, though I don't know what you mean about requiring the brackets [...] ?
Jimmy,30,[Ford,BMW,Fiat] <- ?
@JonasW. Oh, I guess I'm confused. I thought the OP was suggesting that they did not want the array still within the string?
@haha can you clarify?
|
2

You can use nested array#reduce. Inside the inner array, check for array and generate comma-separated array and appended the result in the result.

var arr = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]],
    result = arr.reduce((r, a) => {
      var arr = a.reduce((res,v) => { 
        var val = Array.isArray(v) ? `[${v.join(',')}]` : v;
        res.push(val);
        return res;
      }, []); 
      return r + arr.join(',') + '\n';
    }, '');
console.log(result);

Comments

1

There is a posible solution... it just formats the third element of each item as string so it can be joined at the end:

var data = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]
var dataAsString = data.map(function(d){ return [d[0], d[1],'[' + d[2].join(',') + ']']})
var output = dataAsString.join(',');

Comments

1

A naive solution would be to use JSON.stringify then use a bit of replace to format it a bit better:

let result = JSON.stringify([["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]])
	.replace(/(\]\]\,)\[/g, "]\n") // Adding new lines and removing starting [
	.replace(/(\[\[|\]\]|\")/g,""); // removing junk
console.log(result);

The clean solution would be to build the string yourself based on the objects you receive

Comments

0

Here is a small recursive function that handles it:

const input = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]];

function toString(input, level) {
    // input is not an array, therefore just return the input itself
    if (!Array.isArray(input)) {
        return input + ",";
    } else {
        if (Array.isArray(input) && level < 2) {
            // first two levels of arrays should be broken down
            let text = "";
            input.forEach(part => text += toString(part, level+1));
            text += "\n";
            return text;
        } else {
                // third level of arrays should just be printed, but without quotes
                let text = JSON.stringify(input);
                while (text.indexOf("\"") > -1) {
                    text = text.replace("\"", "");
                }
                return text;
        }
    }
}

const result = toString(input, 0)
console.log(result);

Comments

0

Simple forEach solution. Uses JS internal Array.toString() functionality for the inner-most array..

var arr=[["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]

var str='';

arr.forEach(function(el) {str += el[0] + ', ' + el[1] + ', [' + el[2] + '] '});

console.log(str);

Comments

-1

You can use lodash to achieve this.

var data = [["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin", 20, ["Ford", "BMW", "Fiat"]]]

var flattenedData = _.flattenDeep(data);

var stringifiedData = _.toString(flattenedData)

console.log(stringifiedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

3 Comments

Or you can use pure JS and not import another extra heavy library
@Antony Why is there a -1? Its a possible answer right?
Excluding the fact that you introduced a totally unwanted library into a pure JS question, the result isn't formatted at all and simply does not answer the question

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.