2017-02-01 3 views
0

すべての単一の整数を 'reduce'の後に取り出すことができましたが、重複がすべてある場合は出力されず、出力は0でなければなりません。どの時点で、単一の整数Javascriptを使用して配列内で単一の整数を見つける

var singleNumber = function(nums) { 
     var sorted_array = nums.sort(); 

     for (var i=0; i < sorted_array.length; i++){ 
     var previous = sorted_array[i-1]; 
     var next = sorted_array[i+1]; 
     var singles = {key: 0}; 
     var singlesArray = []; 

     if (sorted_array[i] !== previous && sorted_array[i] !== next){ 
      singlesArray.push(sorted_array[i]); 

      singlesArray.reduce(function(singles, key){ 
       singles.key = key; 
       //console.log('key', key); 
       return singles.key; 
      },{}); 

     } 
     else if(singlesArray.length === 0) { 
      singles.key = 0; 
      return singles.key; 
     } 
    } 
    console.log('singles.key', singles.key); 
    return singles.key; 
    }; 

    console.log(singleNumber([2,1,3,4,4])); 
+0

対あなたは 'singleNumber()'範囲内の 'singles'変数に代入します。 'singles'にゼロ以外の値を代入するのはクロージャのスコープの内側だけです。 – Phylogenesis

+0

ありがとうございます@Phylogenesis私はあなたが言っているが、シングルナンバー()スコープ内で非ゼロの値を割り当てる方法についてついています。私はforループとsingleNumber()内で、0のままでシングルスを動かそうとしました。 – gmatsushima

+0

他の誰もが考えていますか?私は条件文を最初の 'if文'に入れ替え、まだsingles.key = 0を得ています。助けていただければ幸いです。 – gmatsushima

答えて

0
// tests 
const n1 = [1,2,3,4,4] //[1,2,3] 
const n2 = [1] //[1] 
const n3 = [1,1] //0 
const n4 = [1,1,1] //0 
const n5 = [1,5,3,4,5] //[1,3,4] 
const n6 = [1,2,3,4,5] //[1,2,3,4,5] 
const n7 = [1,5,3,4,5,6,7,5] //[1,3,4,6,7] 

const singleNumber = numbers => { 

    const reducer = (acc, val) => { 
    // check to see if we have this key 
    if (acc[val]) { 
     // yes, so we increment its value by one 
     acc[val] = acc[val] + 1 
    } else { 
     // no, so it's a new key and we assign 1 as default value 
     acc[val] = 1 
    } 
    // return the accumulator 
    return acc 
    } 

    // run the reducer to group the array into objects to track the count of array elements 
    const grouped = numbers.reduce(reducer, {}) 

    const set = Object.keys(grouped) 
    // return only those keys where the value is 1, if it's not 1, we know its a duplicate 
    .filter(key => { 
     if (grouped[key] == 1) { 
     return true 
     } 
    }) 
    // object.keys makes our keys strings, so we need run parseInt to convert the string back to integer 
    .map(key => parseInt(key)) 

    // check to array length. If greater than zero, return the set. If it is zero, then all the values were duplicates 
    if (set.length == 0) { 
    return 0 
    } else { 
    // we return the set 
    return set 
    } 
} 

console.log(singleNumber(n7)) 

https://jsbin.com/sajibij/edit?js,console

+0

ありがとうございます@ケビン..私は実際にjsbin経由で次の幸運を尽くしましたが、私が目指すことができ、 )ありがとうございますhttps://jsbin.com/herapozite/1/edit?js,console – gmatsushima

関連する問題