如何在js中分离数组

时间:2017-06-20 06:34:27

标签: javascript angularjs node.js mean-stack

我有82个项目的数据,我想在一个文件中写入10个。我如何分离数组,这样我每个得到10个,另一个文件得到2个。

我的代码,

 var data  = [];
 data.forEach(function(i,v) {
   if((v != 0) && (v%10 === 0)) {
      var appendData = blogList.splice(0,10);
      fs.writeFile(appendData){

      }
   }

我有82个项目的数据,我想在一个文件中写入10个。我如何分离数组,这样我每个得到10个,另一个文件得到2个。

但是我收到了文件中的前10个项目。任何人都可以帮助我。谢谢。

4 个答案:

答案 0 :(得分:1)

对此的简单解决方案是:

let chunk = 10;
for (let i=0,j=blogList.length ; i<j ; i+=chunk) {
    let  appendData = blogList.slice(i,i+chunk);
    fs.writeFile(appendData){
        .....
    }
}

只有前10个进入文件

let  appendData = blogList.slice(0,10);
fs.writeFile(appendData){
    .....
}

答案 1 :(得分:0)

每次达到10个元素时,您必须获取新文件。如果当前索引不是10的倍数,那么您只需将该值添加到当前文件

var data = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
var myFile = "";//Get new file
data.foreach((x, i){
  if(i%10===0){
    myFile = ...//Get new file
  }
  myFile.writeFile(x){...}//Add the data to the file
});

答案 2 :(得分:0)

使用此代码,var admin = require('./routes/admin'); var viewer = require('./routes/viewer'); app.get('/', function(req,res,...) { if (req is admin) app.use('/', admin); else app.use('/', viewer); }); array objects{group: n, data:[]},您可以ng-repeat

使用data

var app = angular.module("app", []);

app.controller("ctrl", ["$scope", function($scope) {

  var data = ["a", "b", "c", "d", "e", "f", "g", "h", "k", "l", "m", "n", "o", "r", "i", "q", "s", "t", "x", "z", "u", "hh"];

  $scope.array = [];
  var index = 1;
  while (data.length) {
    var object = {
      group: index++,
      data: []
    };
    object.data = data.splice(0, 10);
    $scope.array.push(object);
  }

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container" ng-app="app" ng-controller="ctrl">
  <ul class="list-group" ng-repeat="object in array">
    <li class="list-group-item active">group {{object.group}}</li>
    <li class="list-group-item" ng-repeat="item in object.data">{{item}}</li>
  </ul>
</div>

答案 3 :(得分:0)

Try this

var data = [];
for(var i=0;i<82;i++){
    data.push(i);
}
var chunkSize = 10;

var arr = data.reduce((acc, item, idx) => {
  let group = acc.pop();
  if (group.length == chunkSize) {
    acc.push(group);
    group = [];
  }
  group.push(item);
  acc.push(group);
  return acc;
}, [[]]);

console.log(arr);