通过首字母从数组中查找和删除元素

时间:2016-08-19 22:17:58

标签: javascript angularjs arrays

我有一个动态数组。值来自方法push的函数,我想能够检查一个数组是否已经有相同字母的元素“X”,所以我想删除这个元素,然后推送新元素。我怎样才能做到这一点? 我的代码

plunker

$headers = array('HeaderName:HeaderValue','HeaderName2:HeaderValue2');

已更新 在@Anton的帮助下,我终于完成了创建正确请求的逻辑。这工作正常plunker。也许它会对某些人有用

3 个答案:

答案 0 :(得分:1)

试试这个

 //Create new Array and put element on it..
 $scope.filter = []
 $scope.TempArr = [];
 var string;
$scope.requestSelected = function(param) {
for (var i = 0; i < $scope.filter.length; i++) {
  if ($scope.filter[i] == param) {
    $scope.TempArr.push(param);
  } else {
    $scope.TempArr.push(param);
  }
  if (i == $scope.filter.length - 1) {
    //$scope.filter=[]; if you want then you can update new element only
    $scope.filter = $scope.TempArr;
    string = $scope.filter.join(";")

    console.log(string)
   }
  }
 }

答案 1 :(得分:1)

您始终在$scope.filter.push(param)添加条件,而不是必须为每个搜索字段分隔不同的字段,并执行以下操作:

           var filterOptions = {
               filterBy: '&$filter=',
               filterParam: "",
               classId: '',
               categoryId: ''
           };

           $scope.selectedCat = [];
           $scope.selectedCl = [];

           $scope.updateCategory = function (categoryId) {

               if ($scope.selectedCat.indexOf(categoryId) > -1) {
                   $scope.selectedCat.splice($scope.selectedCat.indexOf(categoryId), 1);
               } else {
                   $scope.selectedCat.push(categoryId);
               }

             filterOptions.categoryId = 'categoryId=in=(' + $scope.selectedCat + ")"

             filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
           console.log(filterOptions.filterParam)
           };

           $scope.updateClass = function (classId) {

               if ($scope.selectedCl.indexOf(classId) > -1) {
                   $scope.selectedCl.splice($scope.selectedCl.indexOf(classId), 1);
               } else {
                   $scope.selectedCl.push(classId);
               }

               filterOptions.classId = 'eventClassId=in=(' + $scope.selectedCl + ")"

               filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
               console.log(filterOptions.filterParam)

           };

答案 2 :(得分:0)

据我了解,您可以这样做(简化名称和函数调用):

var filter = ["abc", "123"], param = "_?!"

var found = filter.indexOf(param);
if (found !== -1) {
  // filter already has an elem with the same letters as param
  filter.splice(found, 1);
}

filter.push(param);

我是否有任何细微差别?