2017-09-28 8 views
0

배열이 증가하는 순서로 정렬되며 일치하는 값을 콜론으로 구분하여 가져 오려고합니다.for 루프에서 일치하는 값을 찾는 JavaScript

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 텍스트가 한 것 : 2 : 1
2, 텍스트는이 될 것이다 5 : 5 : 5

+1

당신은 루프 – yBrodsky

+0

내가 당신을 아주 달성하기 위해 원하는 것을 얻을하지 않습니다 둥지해야합니다. 왜 모든 것을 같은 텍스트 변수에 저장합니까? 배열을 텍스트로 인쇄하려면 더 쉬운 방법이 있습니다. 각 번호 텍스트를 저장하려는 경우 배열에서 이것은 Array.reduce() 작업처럼 들린다. –

답변

-1

I 2
5 텍스트가 5 것 네가 성취하려는 것을 확실히 모르겠다. 이게 네가 찾고있는 일이되기를 바란다. 당신은 당신이 제공하는 입력에 따라 문자열을 얻고 싶은 경우에

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);

는, 아마도이 더 낫다 :

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)}"`));

0

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]) 
 
}

1

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