JSFiddle - React, Tailwind, and code Playground
by podgorniy
JavaScript
'use strict';
function isArray (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function flatten(arr) {
function toString(obj) {
var result = '';
var tmp_res = [];
if (isArray(obj)) {
for (var i=0; i<obj.length; ++i) {
tmp_res[tmp_res.length] = toString(obj[i]);
}
result = '[' + tmp_res.join(', ') + ']';
}
else if (isObject(obj)) {
for (key in obj) {
tmp_res[tmp_res.length] = key + ': ' + toString(obj[key])
}
result = '{' + tmp_res.join(', ') + '}';
}
else {
result = obj
}
return result;
}
var result = [];
for (var i=0; i<arr.length; ++i) {
if (isArray(arr[i])) {
var val = arr[i];
if (val.length === 0) {
result[result.length] = '[]';
continue;
}
for (var j=0; j<val.length; ++j) {
result[result.length] = toString(val[j]);
}
}
else if (isObject(arr[i])) {
result[result.length] = toString(arr[i]);
}
else {
result[result.length] = arr[i];
}
}
return '[' + result.join(', ') + ']';
}
var arr = [{}];
var obj = arr[0];
var flatArr = flatten(arr);
console.log(flatArr[0] === obj); // expected true, but false