我有一个像let x = [1,5,2,6,7,9]
但是我想将其作为对象数组,例如下面的代码映射或JSON
let y = [
{ st:1,ed:2},
{st:5,ed:7},
{st:9,ed:9}
]
根据数字的连续性,需要任何帮助或建议
答案 0 :(得分:2)
您可以对数组进行排序并通过插入新对象或在末尾更新数组来缩小数组,具体取决于第一项或最后一个值不在短范围内。
部分:
.sort((a, b) => a - b)
通过获取两个元素的增量对数组进行排序,并返回使用
Array#some
所需的值。排序后的数组看起来像[1, 2, 5, 6, 7, 9]
更复杂的部分是使用
Array#reduce
返回对象的最终数组。.reduce((accumulator, value, index) => { if (!index || accumulator[accumulator.length - 1].end + 1 < value) { accumulator.push({ start: value, end: value }); } else { accumulator[accumulator.length - 1].end = value; } return accumulator; }, []);
在
index
为零的开头,第一个对象被推到accumulator
。然后它从数组中获取下一个值,而
!1
不为true时,检查的第二部分accumulator[accumulator.length - 1].end + 1 < value
被求值并返回
false
,因此else部分将更新end
属性。最后,累加器被返回并包含所需的结果。
var array = [1, 5, 2, 6, 7, 9],
result = array
.sort((a, b) => a - b)
.reduce((accumulator, value, index) => {
if (!index || accumulator[accumulator.length - 1].end + 1 < value) {
accumulator.push({ start: value, end: value });
} else {
accumulator[accumulator.length - 1].end = value;
}
return accumulator;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以像下面一样使用Array.sort
,Array.filter
和Array.flatMap
sort
将按递增顺序对数组进行排序,并导致-[1,2,5,6,7,9]
filter
将过滤那些用左,右值检查时其值是连续的结果,因此将导致-[1,2,5,7,9]
,因为只有6
是具有与左值和右值相比,值1的正好差异
flatMap
然后将遍历以上结果并准备所需的输出
let x = [1,5,2,6,7,9]
let res = x.sort()
.filter((d, i, t) => !(d == t[i-1] + 1 && d == t[i+1] - 1))
.flatMap((d, i, t) => i%2 == 0 ? [{ st: d, en: t[i+1] || d }] : [])
console.log(res)