压缩数组以对连续元素进行分组 [英] Compress array to group consecutive elements

查看:40
本文介绍了压缩数组以对连续元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码压缩一个数组,这样我就可以看到在一个数组中看到一个值的次数:

Following code compress one array so I can see how many times a value was seen in the array:

var str = "shopping-shopping-coupons-shopping-end";
var arr = str.split("-");

function compressArray(original) {
 
	var compressed = [];
	// make a copy of the input array
	var copy = original.slice(0);
 
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
 
		var myCount = 0;	
		// loop over every element in the copy and see if it's the same
		for (var w = 0; w < copy.length; w++) {
			if (original[i] == copy[w]) {
				// increase amount of times duplicate is found
				myCount++;
				// sets item to undefined
				delete copy[w];
			}
		}
 
		if (myCount > 0) {
			var a = new Object();
			a.value = original[i];
			a.count = myCount;
			compressed.push(a);
		}
	}
 
	return compressed;
};

console.log(compressArray(arr));

但是,仅当元素连续重复时,我才需要对它们进行分组.因此,我想要的输出应该是:

However, I need to group elements only if they are repeated consecutively. Therefore, my desired output should be:

[{"value": "shopping", "count": 2},
 {"value": "coupons", "count": 1},
 {"value": "shopping", "count": 1},
 {"value": "end", "count": 1}]

我应该在哪里修改函数,以防止元素(如果元素不连续)被计入键?

Where should I modify the function so I prevent elements to be counted in a key if they are not consecutive?

推荐答案

您可以减少值并检查最后一个值是否等于实际值,然后增加最后一个计数或添加新对象.

You could reduce the values and check if the last value is equal to the actual one, then increment last count or add a new object.

function compressArray(original) {
    return original.reduce((r, value) => {
        var last = r[r.length - 1];
        if (last && value === last.value) {
            last.count++;
        } else {
            r.push({ value, count: 1 });
        }
        return r;
    }, []);
};

var str = "shopping-shopping-coupons-shopping-end",
    arr = str.split("-");

console.log(compressArray(arr));

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

这篇关于压缩数组以对连续元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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