Javascript 如何将两个数组减少为同一索引中存在的单个值?
我有一个D3程序,它正在构建一个有两条线的折线图,我想确定线交叉处的坐标。D3有这个功能吗?数组通常具有不同的长度,并且是动态生成的,但总是有一个值,在同一索引中,两个值相等 e、 g 在这种情况下,答案=索引2。如果没有D3功能,那么使用ES6及以上版本的最佳方法是什么Javascript 如何将两个数组减少为同一索引中存在的单个值?,javascript,arrays,d3.js,Javascript,Arrays,D3.js,我有一个D3程序,它正在构建一个有两条线的折线图,我想确定线交叉处的坐标。D3有这个功能吗?数组通常具有不同的长度,并且是动态生成的,但总是有一个值,在同一索引中,两个值相等 e、 g 在这种情况下,答案=索引2。如果没有D3功能,那么使用ES6及以上版本的最佳方法是什么 const [longer, shorter] = line1.length > line2.length ? [line1, line2] : [line2, line1]; const crossIndex = s
const [longer, shorter] = line1.length > line2.length ? [line1, line2] : [line2, line1];
const crossIndex = shorter.reduce((crossIndex, value, index) => {
if (crossIndex !== null) {
// already found it! just return
return crossIndex;
}
// find it! return
if (value === longer[index]) return index;
// no found, continue searching
return crossIndex;
}, null)
如果您不介意搜索运行一些额外的无用迭代,那么我们发现哪一行更长或更短的第一步实际上是不必要的。在第1行或第2行调用
.reduce()
,然后再次比较另一行,仍然会得到相同的结果 D3有一个非常未知的方法,名为,我们可以使用它来合并数组并查找所有元素相等的任何内部数组:
var line1=[0,1,2,3,4];
变量line2=[4,3,2,1,0];
var zip=d3.zip(第1行,第2行).reduce(函数(a,c,i){
如果(c[0]==c[1])a.push(i);
返回a;
}, []);
console.log(zip)
const [longer, shorter] = line1.length > line2.length ? [line1, line2] : [line2, line1];
const crossIndex = shorter.reduce((crossIndex, value, index) => {
if (crossIndex !== null) {
// already found it! just return
return crossIndex;
}
// find it! return
if (value === longer[index]) return index;
// no found, continue searching
return crossIndex;
}, null)