Jquery: Put split arrays into an array without matching them

I have an input that could be as follows:

"a"

or

  ["a","b"]

or

  [["a","b"],["c"]] 

the goal is to convert them to a third template. I mean, I need a large array containing several arrays. as pseudo code, I try as below:

  input=[].concat(input);
  for (var t in input)
   {
     t=[].concat(input);
   }

but it does not work for the second template, as I want [["a","b"]].

"a"=>[["a"]]

and

  ["a","b"]=>[["a","b"]]

and

  [["a","b"],["c"]] => [["a","b"],["c"]] 
+4
source share
2 answers

You can check if a given value is an array, and if the inner element is also an array, and if not, wrap the value in an array.

function convert(v) {
    if (!Array.isArray(v)) {
        v = [v];
    }
    if (!Array.isArray(v[0])) {
        v = [v];
    }
    return v;
}

console.log(convert("a"));                 // [["a"]]
console.log(convert(["a", "b"]));          // [["a", "b"]]
console.log(convert([["a", "b"], ["c"]])); // [["a", "b"], ["c"]]
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result

If you need to check every element of the internal array, you can check all elements first.

function convert(v) {
    if (!Array.isArray(v)) {
        v = [v];
    }
    if (v.some(function (a) { return !Array.isArray(a); })) {
        v = [v];
    }
    return v;
}

console.log(convert("a"));               // [["a"]]
console.log(convert(["a", "b"]));        // [["a", "b"]]
console.log(convert([["a", "b"], "c"])); // [[["a", "b"], "c"]]
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result
+2

:

var inputs = ["a", ["a","b"],[["a","b"],["c"]]],
    result = inputs.map(a => [[].concat(...a)]);
console.log(JSON.stringify(result));
Hide result
0

Source: https://habr.com/ru/post/1664906/


All Articles