排序数组并按出现次数分组

时间:2019-02-12 06:09:27

标签: javascript arrays

输入

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

输出将是

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

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

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

function answer(ArrayFromAbove) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    for (var j = 0; j < (length - i - 1); j++) {
      if (array[j] > array[j + 1]) {
        var tmp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = tmp;

      }
    }
  }
}
answer(array);
console.log(array);

应返回:

  

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

9 个答案:

答案 0 :(得分:2)

您可以考虑改用reduce,计算每个数字的出现次数,然后遍历已排序的条目并将值推入结果数组(作为数组,如果有多个值,或者只是一个纯数字(如果只有一个)):

const input = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
/* create an object like:
{
  "1": 4,
  "2": 3,
  "4": 1,
  "5": 1,
  "10": 1,
  "20": 2,
  "391": 1,
  "392": 1,
  "591": 1
} */
const inputCounts = input.reduce((a, num) => {
  a[num] = (a[num] || 0) + 1;
  return a;
}, {});

const output = Object.entries(inputCounts)
  // turn (string) key to number:
  .map(([key, val]) => [Number(key), val])
  .sort((a, b) => a[0] - b[0])
  .reduce((a, [num, count]) => {
    a.push(
      count === 1
      ? num
      : new Array(count).fill(num)
    );
    return a;
  }, []);
console.log(output);

答案 1 :(得分:1)

首先使用Set Array.prototype.sort() 删除重复项。获取数组中的数字计数,并fill()和新的Arraypush()进行输出。

const array=[1,2,4,591,392,391,2,5,10,2,1,1,1,20,20]
function count(arr,num){
  return Array(arr.filter(x => x === num).length).fill(num);
}
const unique = [...new Set(array)].sort((a,b) => a -b);
const output = unique.map(un => {
  let arr = count(array,un);
  return (arr.length > 1) ? arr : un;
})
console.log(output)

upper方法正在遍历数组。您可以按照以下方法循环两次来完成

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 = [];
for(let i = 0;i<array.length + 1;++i){
  if(array[i - 1] === array[i] || i === 0){
    temp.push(array[i]);
  }
  else{
    result.push((temp.length === 1) ? temp[0] : temp);
    temp = [array[i]];
  }
}
//result.push(temp)
console.log(result);

答案 2 :(得分:0)

您可以计算发生的次数,然后根据计数创建数组:

 const counts = new Map;

 for(const value of array.sort())
   counts.set(value, (counts.get(value) || 0) + 1);

const result = [];

for(const [count, value] of counts.entries())
  result.push(new Array(count).fill(value));

答案 3 :(得分:0)

您可以尝试关注

  • 使用Array.sort
  • 对数组进行排序
  • 使用Array.reduce创建结果数组
    • 对于第一个值,只需将值添加到结果数组中
    • 对于所有下一个值,请检查结果数组中的最后一个值是否为数组
    • 如果最后一个值是数组,则将数组中的第一个值与当前值匹配。
      • 如果值相同,则将其推到最后一个值数组
      • 否则将其推入主结果数组
    • 否则将最后一个值与当前值匹配
      • 如果值相同,则用包含2个值的数组替换结果数组中的条目
      • 否则将其推入主结果数组

let array = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
let result = array.sort((a,b) => a-b).reduce((a,c) => {
  if(a.length) {
    let lastVal = a[a.length-1];
    if(Array.isArray(lastVal)) {
      if(lastVal[0] == c) lastVal.push(c);
      else a.push(c);
    } else if(lastVal == c) a[a.length-1] = [c,c];
    else a.push(c);
  }
  else a.push(c);
  return a;
}, []);

console.log(result);

答案 4 :(得分:0)

您可以根据数字的出现次数使用减少和填充数组

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

let reduced = array.reduce((op,inp)=>((op[inp] ? op[inp]++ : (op[inp]=1)),op),{})

let op = Object.keys(reduced).map(e=>(reduced[e] === 1 ? e : new Array(reduced[e]).fill(e)))
        .sort((a,b)=> (Array.isArray(a) ? a[0] : a) - (Array.isArray(b) ? b[0] : b) )

console.log(op)

答案 5 :(得分:0)

对数组进行排序,将所有数字分组为一个子数组,然后仅用该元素中的一个元素替换这些数组。

var array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
function answer(arr){
	arr.sort((a,b) => a - b);
	var tempResult = [];
	while(arr.length > 0){
		var val = arr.shift();
		if(tempResult.length == 0 || tempResult[tempResult.length-1][0] !== val){
			tempResult.push([val]);
        }else{
			tempResult[tempResult.length-1].push(val);
        }
    }
	
	while(tempResult.length > 0){
		var subArr = tempResult.shift();
		if(subArr.length == 1) arr.push(subArr[0]);
		else arr.push(subArr);
    }
	
}
answer(array);
console.log(JSON.stringify(array));

答案 6 :(得分:0)

使用<?php namespace Tuurbo\Spreedly; use GuzzleHttp\Client as Guzzle; class Spreedly { protected $config; public function __construct($config) { $this->setConfig($config); } public function gateway($token = null) { return new Gateway($this->client(), $this->config, $token); } public function payment($paymentToken = null) { return new Payment($this->client(), $this->config, $paymentToken, $this->gateway()->getToken()); } public function transaction($token = null) { return new Transaction($this->client(), $this->config, $token); } public function setConfig(array $config) { $this->config = $config; $this->validateConfig(); // this is where I have problem return $this; } protected function validateConfig() { // if (!isset($this->config['key'])) { if(!isset(($this->config['spreedly']['key']))){ // this is suppose to be fail throw new Exceptions\InvalidConfigException(); // this is thrown } if (!isset($this->config['secret'])) { throw new Exceptions\InvalidConfigException(); } } public function client() { return new Client(new Guzzle(), $this->config); } } Array.reduce()将重复项累积到一个对象中,然后根据重复项的键将元素过滤并映射到一个新数组中。

Array.sort()

答案 7 :(得分:0)

这是我的实现方式

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

function answer (input) {
  return input.sort((a,b) => a - b)
    .reduce((collect, next) => {
      // First item, just add it
      if (!collect.length) {
        collect.push(next)
        return collect
      }
      let prev = collect.pop()
      if (Array.isArray(prev)) {
        let [ num ] = prev
        if (num === next) {
          prev.push(next)
          collect.push(prev)
          return collect
        } else {
          collect.push(prev, next)
          return collect
        }
      } else if ( prev === next ) {
        collect.push([prev, next])
        return collect
      } else {
        collect.push(prev, next)
        return collect
      }
    }, []);
}

console.log(answer(array));

答案 8 :(得分:0)

var array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]
var resultArray = []
var subArray = []
var length = array.length;
array.sort(function sortArray(a,b) {
    return a - b;
});
for(var i = 0; i < length; i++)
{
    if(subArray.length == 0 || subArray[0] == array[i])
    {
        subArray.push(array[i]);
    }
    else if(subArray.length > 1 && array[i] != subArray[0])
    {
        resultArray.push(subArray);
        subArray = [array[i]];     
    }
    else if(subArray.length == 1 && array[i] != subArray[0])
    {
        resultArray.push(subArray[0]);
        subArray = [array[i]];
    } 
}
if(subArray.length == 1)
{
    resultArray.push(subArray[0]);
}
else
{
    resultArray.push(subArray);
}
console.log(resultArray);
//return(resultArray);