JS按组分组数组值 [英] JS group array values by groups

查看:268
本文介绍了JS按组分组数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将数组值保存到组中

I cant save array values into groups:

我有一个像这样的数组:

I have an array like this:

 ["0", "2", "8", "8", "8", "8", "8", "8", "2", "9", "9", "9", "9", "9", "2", "10", "10", "10", "10", "10", "10", "10", "10", "0", "3", "11", "11",.....]

我需要的是将值分组并保存到这样的对象中:

what I need is to group values and save to object like this:

{0 = 1, 2 = 1, 8 = 6, 2 = 1, 9 = 5, 2 = 1, 10 = 9, 0 = 1,...}

我尝试了几种方法,但是没有运气

I tried several ways but no luck

var max = 0;
var group = {};
for (var i = items.length; --i >= 0; ) {
    var value = items[i];
    var n = group[value] = 1 - -(group[value] | 0);
    if (n > max) {
        max = n;
    }
}

这将返回所有求和值,例如:{0=6, 2=7,...}

This one returns all summed values like: {0=6, 2=7,...}

这还会返回错误的结果:

This also returns me wrong result:

var j = 1,
        value = 0,
        valueArray = {};

for (i = 0; i <= items.length; i++) {
    if (value == items[i]) {
        j++;
    } else {
        valueArray[j] = value;
        j = 1;
    }
    value = items[i];
}

有什么建议吗?

推荐答案

我认为您试图在JS中实现是不可能的-根据您编写的内容,您的输出对象将具有例如两个键值为0(或三个键值为2)

I think what you're trying to achieve in JS is impossible - according to what you've written, your output object would have, for example, two keys with value 0 (or three keys with value 2)

可能的确是分组,但与提供的输出不符:

What is possible, is indeed grouping, but not according to your provided output:

var input = ["0", "2", "8", "8", "8", "8", "8", "8", "2", "9", "9", "9", "9", "9", "2", "10", "10", "10", "10", "10", "10", "10", "10", "0", "3", "11", "11"];

var output = [];
for (var i=0; i<input.length; i++)
{
    if (!output[output.length-1] || output[output.length-1].value != input[i])
        output.push({value: input[i], times: 1})
    else
        output[output.length-1].times++;
}

console.log(output);

提琴: http://jsfiddle.net/UCbkz/

在输出数组中,您将得到一组数字,就像它们在输入数组中一样,所以:

In the output array, you'll end up with groups of numbers as they are in your input array, so:

  • 0 =>值:0,次:1
  • 1 =>值:2,时间:1
  • 2 =>值:8,次数:6
  • 3 =>值:2,时间:1
  • ...

这篇关于JS按组分组数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆