Home > Blockchain >  write a function () that returns the count of all elements and arrays including nested arrays?
write a function () that returns the count of all elements and arrays including nested arrays?

Time:01-26

using recursion and the ternary operator . I will be very grateful if you explain how it is arranged.`

 console.log (deepCount([]));
0
 console.log (deepCount([1 ,2 ,3]));
3
 console.log (deepCount(["x", "z", ["y"]]));
4
 console.log (deepCount([1, 2,[3, 4,[5]]]));
7
 console.log (deepCount([[[[]]]]));
3   

let arr = [1, 2, [3, 4[5]]];

function deepCount(arr) {
  let result = arr.length;
  for (const char of arr) {
    if (Array.isArray(arr[char])) {
      result  = arr[char];
      deepCount(arr);
    }
    return result;
  };    

CodePudding user response:

Asked: using recursion and a ternary operator :

For my part (in addition to the remarks made by Barmar), your first error is to not have indent your code : it's a simple way to check the parity of your braces. I recommend the Whitesmiths style, of course.

K&R and other styles with "Egyptian braces" are unsuitable for this check...

console.log( deepCount( []                ));     // --> 0
console.log( deepCount( [1 ,2 ,3]         ));    // --> 3
console.log( deepCount( ["x", "z", ["y"]] ));   // --> 4
console.log( deepCount( [1, 2,[3, 4,[5]]] ));  // --> 7
console.log( deepCount( [[[[]]]]          )); // --> 3   

function deepCount( arr )
  {
  let count = arr.length;
  for (const elm of arr) 
    {
    count  = Array.isArray(elm) ? deepCount(elm) : 0;
    }
  return count;
  }

The same, in a "single" line of code:

const deepCount = arr =>
  arr.reduce((N,x)=>N =(Array.isArray(x)?deepCount(x):0),arr.length);

console.log( deepCount( []                ));     // --> 0
console.log( deepCount( [1 ,2 ,3]         ));    // --> 3
console.log( deepCount( ["x", "z", ["y"]] ));   // --> 4
console.log( deepCount( [1, 2,[3, 4,[5]]] ));  // --> 7
console.log( deepCount( [[[[]]]]          )); // --> 3   

CodePudding user response:

  1. When you use for-of, the iteration variable is the array element, not its index. So you should use char, not arr[char]. I've renamed char to element, since it has nothing to do with characters.
  2. You need to add the value returned from the recursive call to result, not add the array element to it.
  3. return result should not be inside the loop, it should be at the end.

function deepCount(arr) {
  let result = arr.length;
  for (const element of arr) {
    if (Array.isArray(element)) {
      result  = deepCount(element);
    }
  };
  return result;
}

console.log(deepCount([]));
console.log(deepCount([1, 2, 3]));
console.log(deepCount(["x", "z", ["y"]]));
console.log(deepCount([1, 2, [3, 4, [5]]]));
console.log (deepCount([[[[]]]]));

  • Related