使用Javascript在数组中查找单个整数

时间:2017-02-01 09:41:45

标签: javascript arrays integer reduce

我能够在'reduce'之后拉出所有单个整数,但是当有所有重复项并且输出应该为0时不能正常工作,而不是命中我的其他或者如果 - 代码保持输出0而不是单个整数

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

1 个答案:

答案 0 :(得分: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