haha
haha

Reputation: 41

nested array to string javascript

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

Upvotes: 4

Views: 13777

Answers (7)

PM 77-1
PM 77-1

Reputation: 13334

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);

Upvotes: 0

fjc
fjc

Reputation: 5815

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);

Upvotes: 0

Antony
Antony

Reputation: 1273

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

Upvotes: 1

arunmmanoharan
arunmmanoharan

Reputation: 2675

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>

Upvotes: -1

zfrisch
zfrisch

Reputation: 8660

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"]]
]) 
);

Upvotes: 3

Hassan Imam
Hassan Imam

Reputation: 22524

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);

Upvotes: 2

Javier Gonzalez
Javier Gonzalez

Reputation: 1015

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(',');

Upvotes: 1

Related Questions