Javascript 仅当值不存在时才使用 lodash 推送到数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37073774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:51:47  来源:igfitidea点击:

Using lodash push to an array only if value doesn't exist?

javascriptarraysangularjslodash

提问by Max Lynn

I'm trying to make an array that if a value doesn't exist then it is added but however if the value is there I would like to remove that value from the array as well.

我正在尝试创建一个数组,如果一个值不存在,则添加它,但是如果该值存在,我也想从数组中删除该值。

Feels like Lodash should be able to do something like this.

感觉像 Lodash 应该能够做这样的事情。

I'm interested in your best practises suggestions.

我对您的最佳实践建议很感兴趣。

Also it is worth pointing out that I am using Angular.js

另外值得指出的是我正在使用 Angular.js

* Update *

* 更新 *

if (!_.includes(scope.index, val)) {
    scope.index.push(val);
} else {
  _.remove(scope.index, val);
}

回答by floribon

The Setfeature introduced by ES6 would do exactly that.

SetES6 引入的特性正好可以做到这一点。

var s = new Set();

// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists

// Removing values
s.delete('world');

var array = Array.from(s);

Or if you want to keep using regular Arrays

或者,如果您想继续使用常规数组

function add(array, value) {
  if (array.indexOf(value) === -1) {
    array.push(value);
  }
}

function remove(array, value) {
  var index = array.indexOf(value);
  if (index !== -1) {
    array.splice(index, 1);
  }
}

Using vanilla JS over Lodash is a good practice. It removes a dependency, forces you to understand your code, and often is more performant.

在 Lodash 上使用 vanilla JS 是一个很好的做法。它消除了依赖性,迫使您理解您的代码,并且通常性能更高。

回答by Afzal Hossain

You can use _.union

你可以使用 _.union

_.union(scope.index, [val]);

回答by S.D.

Perhaps _.pull()can help:

也许_.pull()可以帮助:

var _ = require('lodash');

function knock(arr,val){ 
   if(arr.length === _.pull(arr,val).length){
      arr.push(val);
   } 
   return arr;
}

Mutates the existing array, removes duplicates as well:

改变现有数组,同时删除重复项:

> var arr = [1,2,3,4,4,5];

> knock(arr,4);
[ 1, 2, 3, 5 ]

> knock(arr,6);
[ 1, 2, 3, 5, 6 ]

> knock(arr,6);
[ 1, 2, 3, 5 ]

回答by alexmac

Use includesfunction to check that item is exists in array, and removeto delete existing item.

使用includes函数检查数组中是否存在项目,并remove删除现有项目。

function addOrRemove(arr, val) {
  if (!_.includes(arr, val)) {
    arr.push(val);
  } else {
    _.remove(arr, item => item === val);
  }
  console.log(arr);
}

var arr = [1, 2, 3];
addOrRemove(arr, 1); // arr = [2, 3]
addOrRemove(arr, 4); // arr = [2, 3, 4]
addOrRemove(arr, 2); // arr = [3, 4]
<script src="https://raw.githubusercontent.com/lodash/lodash/4.11.2/dist/lodash.min.js"></script>

回答by Darlan Dieterich

In this case you can use 'concat' to push and 'uniq' to validate unique values:

在这种情况下,您可以使用“ concat”推送并使用“ ”uniq验证唯一值:

example:

例子:

var ar = [1, 2, 3, 1, 5, 2, 4]
ar = _.uniq(_.concat(ar, 9))
//[1, 2, 3, 5, 4, 9]

e.g.: https://codepen.io/dieterich/pen/xeZNJY

例如:https: //codepen.io/dieterich/pen/xeZNJY

ref.: https://lodash.com/docs/4.17.11#uniq

参考:https: //lodash.com/docs/4.17.11#uniq

回答by Ilya Lagoshny

The simplest way to do this is use _.isEmpty and _.remove Lodash functions:

最简单的方法是使用 _.isEmpty 和 _.remove Lodash 函数:

if (_.isEmpty(_.remove(array, value)) {
   array.push(value);
}

After remove function will be return removed values or an empty array, and if return an empty array then we will add a new value.

remove 函数将返回删除的值或一个空数组,如果返回一个空数组,则我们将添加一个新值。

回答by Rich Howell

If you don't need to support IE, or if you are using polyfills, you can use Array.prototype.includes()

如果你不需要支持 IE,或者你正在使用 polyfills,你可以使用Array.prototype.includes()

const addUniq = (array, value) => array.includes(value) 
  ? array.length 
  : array.push(value);

回答by Redu

This single liner should do the job. If element to be inserted does not exist, it inserts the element and returns the length of the resulting array. If element exists in the array it deletes the element and returns the deleted element in a separate array.

这个单衬应该可以完成这项工作。如果要插入的元素不存在,则插入该元素并返回结果数组的长度。如果元素存在于数组中,则删除该元素并在单独的数组中返回已删除的元素。

var arr = [1,2,3,4,5],
    aod = (a,e,i=0) => !!~(i = a.indexOf(e)) ? a.splice(i,1) : a.push(e); 
    
document.write("<pre>" + JSON.stringify(aod(arr,6)) + JSON.stringify(arr) + "</pre>");
document.write("<pre>" + JSON.stringify(aod(arr,6)) + JSON.stringify(arr) + "</pre>");

Well actually i hate push since it returns the resulting array length value which is most of the time useless. I would prefer to have a reference to the resulting array to be returned so that you can chain the functions. Accordingly a simple way to achieve it is;

好吧,实际上我讨厌推送,因为它返回结果数组长度值,这在大多数情况下是无用的。我希望有一个对要返回的结果数组的引用,以便您可以链接这些函数。因此,实现它的简单方法是;

var arr = [1,2,3,4,5],
    aod = (a,e,i=0) => !!~(i = a.indexOf(e)) ? a.splice(i,1) : (a.push(e),a);
        
document.write("<pre>" + JSON.stringify(aod(arr,6)) + JSON.stringify(arr) + "</pre>");
document.write("<pre>" + JSON.stringify(aod(arr,6)) + JSON.stringify(arr) + "</pre>");

So now this is reasonably chainable.

所以现在这是可以合理链接的。