排序数组并按输入类型分组

时间:2019-02-12 12:38:31

标签: javascript arrays

输入

 array=[1,2,4,591,392,"391","2",5,10,2,1,1,1,20,20]

输出将是

 array=[[[ 1, 1, 1, 1 ], [ 2, 2 ], 4, 5, 10, [ 20, 20 ], 392, 591],["391","2"]]

另一个例子是输入

 array= [1, "2", "3", 2]

,输出为:

 array=[[1,2],["2","3"]]

尝试了以下功能来创建结果:

let array=[1,2,4,591,392,"391","2",5,10,2,1,1,1,20,20]
array = array.sort((a,b) => a-b);
const result = [];
let temp = [];
let temp2 = [];
for(let i = 0;i<array.length + 1;++i){
  if(typeof(array[i]) === "string" ){
  temp2 = [array[i]];
  console.log( temp2);
  }
  else if(array[i - 1] === array[i] || i === 0){
  temp.push(array[i]);
  }
  else{
      result.push((temp.length === 1) ? temp[0] : temp);
  temp = [array[i]];
  }              
  }

console.log(result);

应返回:

  

[[[[1,1,1,1],[2,2],4,5,10,[20,20],392,591],[“ 391”,“ 2”]]

4 个答案:

答案 0 :(得分:1)

您可以按类型和按值分组。对于结果,如果存在多个元素,则仅获取数组。

var array = [1, 2, 4, 591, 392, "391", "2", 5, 10, 2, 1, 1, 1, 20, 20],
    result = Object
        .values(array.reduce((r, v) => {
            var t = typeof v,
                k = JSON.stringify(v); // sort only numbers, not strings
            r[t] = r[t] || {}
            r[t][k] = r[t][k] || [];
            r[t][k].push(v);
            return r;
        }, {}))
        .map(o => Object.values(o).map(a => a.length === 1 ? a[0] : a));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

const array = [1,2,4,591,392,"391","2",5,10,2,1,1,1,20,20]

const f = () => {
  // create array just for strings
  const strings = []
  // create object to find repeating numbers
  const numbers = {}
  // result we will return
  const result = []
  // iterating through the array
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    // collecting all strings to strings array
    if (typeof item === 'string') {
      strings.push(item)
      // exiting the loop
      continue;
    }
    // check if property item exists
    // "item" property will be one number from our array
    // if not exists we are assigning empty array to this propery
    // if exists we are keeping existing numbers
    numbers[item] = numbers[item] || []
    // push item to array of same items
    numbers[item].push(item)
  }
  // gather strings
  result.push(strings)
  // iterate through collection of similar numbers
  Object.keys(numbers).forEach(key => {
    // if we have multiple repeating numbers we push array of those numbers
    if (numbers[key].length > 1) {
      result.push(numbers[key])
    // else we are extracting the only walue and pushing it
    } else {
      result.push(...numbers[key])
    }
  })
  console.log(result)
}

f(array)

答案 2 :(得分:0)

您可以使用reduceObject.values

做类似的事情

const array = [1,2,4,591,392,"391","2",5,10,2,1,1,1,20,20],
      stringArray = [];

const merged = array.reduce((r,n) => {
  typeof n === "string"
    ? stringArray.push(n)
    : (r[n] = r[n] || []).push(n);
    
  return r;
},{})

const intArray = Object.values(merged).map(a => a.length > 1 ? a : a[0]),
      final = [intArray, stringArray];
      
console.log(final)

reduce内,检查类型是字符串还是数字。使用accumulator对数字进行分组。

然后使用map检查每个组是否具有length > 1并相应地创建intArray。然后将intArraystringArray

答案 3 :(得分:0)

稍微编辑一下代码

let array=[1,2,4,591,392,"391","2",5,10,2,1,1,1,20,20]
array = array.sort((a,b) => a-b);

let result = [];
let resultNumbers = [];
let temp = [];
let temp2 = [];
lastNumber = 0;
for(let i = 0;i<array.length + 1;++i){
  if(typeof(array[i]) === "string" ){
    temp2.push(array[i]);
  }
  else if(lastNumber === array[i] || i === 0){
    temp.push(array[i]);
    lastNumber = array[i];
  }
  else{
     resultNumbers.push((temp.length === 1) ? temp[0] : temp);
     temp = [array[i]];
     lastNumber = array[i];
  }              
  }
result.push(resultNumbers);
result.push(temp2);
console.log(result);