1

I currently split a list in json to first 10 and the second is 11 to 20. However, I want to split it to half for any length of the list. How can I do it?

This is my code

  function loadTop() {
    $webServicesFactory.get($marketProvider[$scope.currentMarket].topGetURL, {AnonymousToken: $marketProvider[$scope.currentMarket].token}).then(
      function success(response) {
        $scope.top = response.Stock.slice(0, 10);
        $scope.low = response.Stock.slice(10, 20);
        console.log($scope.top);
        loadStockCount();
        loadTop();
        loadLow();
        $ionicLoading.hide();
      },
      function error(error) {
        $ionicLoading.hide();
      }
    );
  }
lotteryman
  • 389
  • 1
  • 6
  • 21
  • I think you are searching for [counting number of objects in object](https://stackoverflow.com/questions/16976904/javascript-counting-number-of-objects-in-object) – Òscar Raya Oct 27 '17 at 14:45
  • 3
    key word is _length_, just use `your_list.length / 2` – Aleksey Solovey Oct 27 '17 at 14:47
  • 1
    Possible duplicate of [Splice an array in half, no matter the size?](https://stackoverflow.com/questions/9181188/splice-an-array-in-half-no-matter-the-size) – Hoyen Oct 27 '17 at 15:48
  • this question has really nothing to do with angularj or ionic-framework. It is a JavaScript question involving arrays. – Hoyen Oct 27 '17 at 15:49

1 Answers1

0
var numStocks = response.Stock.length;
var halfStocks = Math.round(numStocks / 2);
$scope.top = response.Stock.slice(0, halfStocks);
$scope.low = response.Stock.slice(halfStocks, numStocks);
danday74
  • 52,471
  • 49
  • 232
  • 283