只保留多个字符串中的一个字符串 - 数组

时间:2014-06-29 13:24:08

标签: javascript html arrays

我只需要从数组中留下一个字符串:

var string = "dog";

var array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"];

看起来很愚蠢,为什么我写了#34; dog"多次,但这只是一个例子。

实际上它会从输入标签创建一个数组。像这样:

  firstEntry = true;

  inputValue = inputfield.value;

  if(inputValue != ''){
      if(firstEntry){
      inputArray.push(inputValue);
      firstEntry = false;
  }

//And know it should leave only one String

  inputValueSplit = inputValue.split(/ /g);
  removeFromArray(inputValueSplit,'');//This is a external function, (deletes empty Strings)
  inputArray = inputValueSplit;


  inputArray.filter(inputValue); // Here it should leave only one 
                                 // String of multiple Strings from
                                 // same value.

我在这里或谷歌都找不到任何东西..

3 个答案:

答案 0 :(得分:1)

不确定你的意思。如果您需要一个仅包含初始数组中的' dog' -values的数组,则可以使用Array.filter

var dogs = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"]
            .filter( function(a){ return a == this; }, 'dog' );
//=> ['dog','dog','dog']

如果你想从初始数组中删除双重“狗”值:

var singleout = 'dog'
   ,dogs = (["dog","cat","bird","snake","tiger","dog", "dog", "cat"]
            .filter( function(a){ return a != this }, singleout ));
// now dogs contains no 'dog' value, so add 'dog' to it again
dogs.push(singleout);
//=> ["cat", "bird", "snake", "tiger", "cat", "dog"]

不使用filter,这是从数组中删除double值的通用方法:

function noDoubles(arr) {
  var doubleChk = {}, noDoubles = []; 
  for (var i=0;i<arr.length;i+=1) { doubleChk[arr[i]] = true; }
  for (var l in doubleChk) { noDoubles.push(l); }
  return noDoubles;
}
noDoubles(["dog","cat","bird","snake","tiger","dog", "dog", "cat"]);
//=> ["dog", "cat", "bird", "snake", "tiger"]

最后,从上一个函数中学习并使用Array.filter,从Array删除双精度可以简单到:

function noDoubles(arr) {
  return arr.filter(function(val) {
     return !this[val] ? ((this[val] = true), true) : false;
    }, {} );    
 }
noDoubles(["dog","cat","bird","snake","tiger","dog", "dog", "cat"]);
//=> ["dog", "cat", "bird", "snake", "tiger"]

Array.filter方法请参见MDN。链接页面还包含一个垫片,用于在旧版浏览器中启用该方法。

答案 1 :(得分:0)

您可以使用自定义filter功能;如果找到一个特定的值,那么它将从那时起被过滤掉:

var string = "dog";
var array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"];

var result = (function() {
    var found = false;

    // @see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
    return array.filter(function(value) {
        if (value == string) {
            // only allow this one time
            return found ? false : found = true;
        }
        return true;
    });
}());

Demo

答案 2 :(得分:0)

好吧,我想如果我有:

array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"]

我希望我能拥有:

array = ["dog","cat","bird","snake","tiger"]

感谢Kooilnc noDouble -function。

这是我需要的完美方式。