0

How do I check particularly using AngularJS if an array has duplicate values?

If more than 1 element of the same exist, then return true. Otherwise, return false.

$scope.intArray = [5, 11, 17, 53] // return false because no duplicates exist
$scope.intArray = [5, 11, 17, 5]  // return true because duplicaets exist
1
  • Just sort the element of the array, and check adjacent elements? Commented Jan 11, 2016 at 19:00

4 Answers 4

2

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
  return (new Set(array)).size !== array.length;
}

Otherwise:

function hasDuplicates(array) {
  var valuesSoFar = Object.create(null);
  for (var i = 0; i < array.length; ++i) {
    var value = array[i];
    if (value in valuesSoFar) {
        return true;
    }
    valuesSoFar[value] = true;
  }
  return false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

it is sad that there is not particularly AngularJS function that checks this, so we have to use pure JavaScript
I think you have a misunderstanding of the purpose of AngularJS.
1

Just sort the array and then run through it and see if the next index is the same as the current.

$scope.intArray = [5, 11, 17, 5];
checkDupes($scope.intArray);

function checkDupes(array)
{
  array.sort(); // use whatever sort you want
  for (var i = 0; o < array.length -1; i++)
  {
    if (array[i+1] == array[i])
    {
      return true;
    }
  }
  return false;
}

2 Comments

That is JavaScript solution, I was thinking about AngularJS function
AngularJS is a framework, it's purpose isn't to give you functions for doing all kinds of data manipulation.
1

http://codepen.io/anon/pen/xZrrXG?editors=101

Created the hasDuplicate as a scope method which could be easily used in your html if need-be.

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

app.controller('mycontroller', ['$scope', function($scope) {
  $scope.intArray = [5, 11, 17, 5];

  $scope.hasDuplicate = function(data) {
    for (var i = 0; i < data.length; i++) {
      for (var x = i + 1; x < data.length; x++) {
        if (data[i] == data[x]) {
          return true;
        }
      }
    }
    return false;
  };
}]);

1 Comment

That is JavaScript solution, I was thinking about AngularJS function
1

You could use lodash library, you could find it very handy sometimes. And implement it like mentioned here: https://stackoverflow.com/a/28461122/4059878

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.