0

i am leaning how to use underscore in AngularJS. i try to extract last 2 element from array and show in alert. code is working but the problem is last two element is showing together in alert but i want to show each element in alert one after one. here is my code. please tell me what i should use as a result each last 2 element in alter one after one.

<div ng-app="myApp" ng-controller="MainCtrl">

</div>

var myApp = angular.module('myApp', []);

myApp.factory('_', function() {
  return window._; //Underscore should be loaded on the page
});

myApp.controller('MainCtrl', function ($scope, _) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];

    var x = _.last($scope.awesomeThings, 2);
        //alert(x[0]);

        _.each([x],function(i)
    {
        alert(i);
    });

  });        

i also follow these links

how to break the _.each function in underscore.js

how to install underscore.js in my angular application?

Plucking an Object in an array using underscore.js

1
  • still got no answer.........waiting :( Commented Jun 15, 2017 at 11:18

2 Answers 2

1

_.last(..., 2) will return an array containing 2 items for you.

var x = _.last($scope.awesomeThings, 2);

_.each loops through the array, so:

_.each([x], function(i) {

Notice how you wrapped x in another array, unnecessarily. It successfully loops through the only item in the array, which is another array containing the data you needed.

Your solution should be as simple as:

_.each(x, function(i) {
  alert(i);
});

Or simpler, like you already noticed you can do:

_.each(x, alert);
Sign up to request clarification or add additional context in comments.

Comments

0

i found out the solution what i was looking for.

these two line solve my issue

var x = _.last($scope.awesomeThings, 2);
_.each(x.reverse(), alert);

full code example

var myApp = angular.module('myApp', []);

myApp.factory('_', function() {
  return window._; //Underscore should be loaded on the page
});


myApp.controller('MainCtrl', function ($scope, _) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];
    //alert('pp');
    /*_.each([1,2,3],function(i)
    {
        alert(i);
    });*/
    var x = _.last($scope.awesomeThings, 2);
    _.each(x.reverse(), alert);
        //alert(x[0]);

        /*_.each([x],function(i)
    {
        alert(i);
    });*/

  });        

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.