简体   繁体   English

在 JavaScript 中将 2D 嵌套数组转换为 1D 数组?

[英]Convert 2D nested array into 1D array in JavaScript?

Given a 2D array as shown in the example, how to manage to combine the string digits into one.给定一个如示例所示的二维数组,如何设法将字符串数字组合成一个。

ex: Array2 = [[1,2,3],[4,5,6],[7,8,9]];例如: Array2 = [[1,2,3],[4,5,6],[7,8,9]];

required sol:所需的溶胶:

Array1 = [123, 245, 789];

You can deconstruct your task into two separate problems, that we will solve in turn.您可以将您的任务分解为两个独立的问题,我们将依次解决。

  1. We need to take an array of numbers (eg [1, 2,3]) and join them together into a string (eg '123').我们需要获取一个数字数组(例如[1, 2,3])并将它们连接成一个字符串(例如'123')。

There is, in fact, a dedicated function for this in JavaScript - the join() function:事实上,在 JavaScript 中有一个专用的 function - join() function:

[1, 2, 3].join(''); // '123'
  1. We need to perform the previous function on each object in an array, returning an array of the transformed objects.我们需要对数组中的每个 object 执行前面的 function,返回转换后的对象数组。

JavaScript again has you covered, this time with the map() function: JavaScript 再次为您服务,这次使用 map() function:

[a, b, c].map((element) => foo(element)); // [foo(a), foo(b), foo(c)]

All we have to do now is join these too together, so that the operation we perform on each element of the parent array, is to join all of the child elements together:我们现在要做的就是将它们也连接在一起,这样我们对父数组的每个元素执行的操作就是将所有子元素连接在一起:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]].map((array) => array.join('')); // ['123', '456', '789']

 function foo(arr){ let toReturn = []; for(let i = 0;i < arr.length;i++){ toReturn.push(arr[i].join("")); } return(toReturn); } console.log(foo([[1,2,3],[4,5,6],[7,8,9]]));

You can use reduce to aggregate your data combined with .join('') to get all element items of each array item into a single value like below:您可以使用reduce来聚合您的数据并结合.join('')将每个数组项的所有元素项变成一个值,如下所示:

 const data = [[1,2,3],[4,5,6],[7,8,9]]; const result = data.reduce((acc, curr) => { acc.push(curr.join('')); return acc; }, []); console.log(result);

Return all files as a 1D array from given path从给定路径将所有文件作为一维数组返回

const fetchAllFilesFromGivenFolder = (fullPath) => {
  let files = [];

  fs.readdirSync(fullPath).forEach(file => {
    const absolutePath = path.join(fullPath, file);
    if (fs.statSync(absolutePath).isDirectory()) {
      const filesFromNestedFolder = fetchAllFilesFromGivenFolder(absolutePath);
      filesFromNestedFolder.forEach(file => {
        files.push(file);
      })
    }
    else return files.push(absolutePath);
  });

  return files
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM