简体   繁体   English

计算序列从一个值变为另一个值的次数

[英]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.

相关问题 在一个数字序列中,如何计算一个数字出现多少次,该值恰好比前一个数字的值小一? - How does one, within a sequence of digits, count how many times a digit appears thats value is exactly one less than the previous digit's one? 计算字符串在另一个字符串中出现的次数 - count how many times a string appears within another string 使用 Javascript,您可以在一秒钟内计数 += 1 多少次? - How many times can you make count += 1 in one second with Javascript? 如何计算一个值在 React 中一小时/一天内有多少次为真? - How to count how many times a value is true in an hour/day in React? 计算表中特定值出现的次数 - Count how many times a specific value appears in a table 计算一个值在对象数组中出现的次数 - Count how many times a value occurs in a array of objects 计算值在数组中出现的次数-Javascript-angular-lodash - Count how many times a value occurs in an array - javascript - angular - lodash 我如何计算一个数组中的属性出现在另一个数组中的次数,以及 map 匹配新数组的次数? - How can I count and the number of times a property from one array appears in another, and map the matches to a new array? 检查一个数组中的值在另一个数组中出现的次数 - Check how many times a value in an array appears in another array 当一个值改变时如何改变另一个值 - when one value changes how to change another value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM