JavaScript在for循环中查找匹配值

时间:2017-09-28 15:01:47

标签: javascript arrays loops sorting matching

数组按递增顺序排序,我希望得到匹配的值,用冒号分隔。

var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5];
var text = "";

for(var i = 0; i < array.length - 1; i++) {
    if(array[0] == array[0 + 1]) {
         text = array[0] + ":" + array[0 + 1]; // 1:1
    }
}

此for循环仅检查两个匹配值。我如何检查所有匹配值的数量?

因此对于1,文本将是1:1
对于2,文本将是2:2:2
对于5,文本将是5:5:5:5

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5]
var text = ''

for(var i = 0; i < array.length; i++) {
    if (array[i] == array[i + 1]) {
         // always add a : suffix
         text += array[i] + ':'; 
    } else {
         // replace the last character with the last value and a new line
         text = text.replace(/.$/, ':' + array[i] + '\n')
    }
}

console.log(text.trim()) // trim the trailing whitespace 
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
var array = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
arrayLength = array.length,
text = {};


for(var i = 0; i < arrayLength; i++) {
    if(!text.hasOwnProperty(array[i])){
      text[array[i]] = []
      for(var e = 0; e < arrayLength; e++){
          if(array[i] == array[e]){
            text[array[i]].push(array[i])
          }
      }
      text[array[i]] = text[array[i]].join(':')
    }
}



//and now you can access to every string by text[number]

for(var key in text){
    console.log(text[key])
}
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

我不太确定你想要实现的目标。我希望这能满足您的需求。

&#13;
&#13;
const 
  input = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
  // Based on the input create a set, each value will appear only once in 
  // the set.
  uniqueIds = new Set(input),
  result = [];

// Iterate over all the unique values of the array.
uniqueIds.forEach(id => {
  // Add the text for the current value to result array.
  result.push(
    // Filter the array, take only the items that match the current value. This
    // will result in a new array that can be joined using a ":" as a
    // separator character.
    input.filter(value => value === id).join(':')
  );
});


// Or on a single line:
// uniqueIds.forEach(id => result.push(input.filter(value => value === id).join(':')));

console.log(result);
&#13;
&#13;
&#13;

如果你想根据你提供的输入得到一个字符串,也许这样更好:

&#13;
&#13;
const 
  input = [1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5],
  textWrapper = (function() {
    let
      array = null,
      cache = {};
      
    function getText(number) {
      if (cache[number] !== undefined) {
        console.log(`Cache hit for number ${number}`);
        return cache[number];
      }
      
      const
        text = array.filter(item => item === number).join(':');
      cache[number] = text;
      
      return text;
    }
      
    function setArray(value) {
      array = value;
      cache = {};
    }
    
    return {
      getText,
      setArray
    }
  })();
  
textWrapper.setArray(input);

const
  values = [1, 3, 5, 5];
  
values.forEach(value => console.log(`Text for ${value} is "${textWrapper.getText(value)}"`));
&#13;
&#13;
&#13;

相关问题