[英]Count how many times sequence changes from one value to another
I have the following sequential array where a car changes colour.我有以下顺序数组,其中汽车会改变颜色。 It starts red and is now yellow in the below example.
在下面的示例中,它开始为红色,现在为黄色。
A = [red,blue,yellow,red,blue]
I need to output is the number of times it went from each colour to each other colour.我需要 output 是它从每种颜色到另一种颜色的次数。
output:
red-blue:2
blue-yellow:1
yellow-red:1
Can this be done in JS?这可以在JS中完成吗? Any help greatly appreciated!
非常感谢任何帮助!
function getColorChangeAmounts(colorChanges){ const colorChangesMap = {}; for(let i = 1; i < colorChanges.length; i++){ const previous = colorChanges[i - 1]; const current = colorChanges[i]; const colorChangeText = previous + "-" + current; const currentCount = colorChangesMap[colorChangeText] || 0; colorChangesMap[colorChangeText] = currentCount + 1; } return colorChangesMap; } const A = ["red", "blue", "yellow", "red", "blue"]; const colorChangesMap = getColorChangeAmounts(A); console.log("output:"); console.log(); console.log(Object.entries(colorChangesMap).map(([key, value]) => key + ":" + value).join("\n"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.