数据变换
🌐 Transforming data
Transform arrays and generate new arrays.
cross(...可迭代对象, 归约函数)
🌐 cross(...iterables, reducer)
d3.cross([1, 2], ["x", "y"]) // [[1, "x"], [1, "y"], [2, "x"], [2, "y"]]如果指定了 reducer,则会对每一个来自每个给定 iterables 的元素组合调用它,并返回相应的归约值。
🌐 If a reducer is specified, it is invoked for each combination of elements from each of the given iterables, and returns the corresponding reduced value.
d3.cross([1, 2], ["x", "y"], (a, b) => a + b) // ["1x", "1y", "2x", "2y"]merge(iterables)
示例 · 来源 · 将指定的 可迭代对象 的可迭代集合合并为一个新的扁平数组。该方法类似于内置的 array.concat 方法,但当你有一个数组的数组或可迭代对象的可迭代集合时使用更方便。
d3.merge([[1], [2, 3]]) // [1, 2, 3]d3.merge(new Set([new Set([1]), new Set([2, 3])])) // [1, 2, 3]pairs(iterable, reducer)
示例 · 来源 · 返回指定可迭代对象中相邻元素的数组,按顺序排列。如果指定的可迭代对象元素少于两个,则返回空数组。
d3.pairs([1, 2, 3, 4]) // [[1, 2], [2, 3], [3, 4]]如果指定了 reducer 函数,它会依次接收来自 iterable 的元素 i - 1 和元素 i。
🌐 If a reducer function is specified, it is successively passed an element i - 1 and element i from the iterable.
d3.pairs([1, 1, 2, 3, 5], (a, b) => b - a) // [0, 1, 1, 2]转置(matrix)
🌐 transpose(matrix)
示例 · 来源 · 使用 zip 运算符作为二维 矩阵转置。
d3.transpose([["Alice", "Bob", "Carol"], [32, 13, 14]]) // [["Alice", 32], ["Bob", 13], ["Carol", 14]]d3.transpose([["Alice", 32], ["Bob", 13], ["Carol", 14]]) // [["Alice", "Bob", "Carol"], [32, 13, 14]]zip(...arrays)
示例 · 来源 · 返回一个数组的数组,其中第 i 个数组包含来自每个参数 arrays 的第 i 个元素。返回的数组长度被截断为 arrays 中最短的数组。如果 arrays 仅包含一个数组,则返回的数组包含单元素数组。如果没有参数,返回的数组为空。
d3.zip(["Alice", "Bob", "Carol"], [32, 13, 14]) // [["Alice", 32], ["Bob", 13], ["Carol", 14]]filter(可迭代对象, 测试函数)
🌐 filter(iterable, test)
来源 · 返回一个新数组,包含 iterable 中按顺序排列且给定的 test 函数返回 true 的值。
d3.filter(new Set([0, 2, 3, 4]), (d) => d & 1) // [3]像 array.filter,但适用于任何可迭代对象。
🌐 Like array.filter, but works with any iterable.
map(可迭代对象, 映射函数)
🌐 map(iterable, mapper)
来源 · 返回一个新数组,包含按给定 mapper 函数定义的从 iterable 映射的值,保持顺序。
d3.map(new Set([0, 2, 3, 4]), (d) => d & 1) // [0, 0, 1, 0]像 array.map,但可以用于任何可迭代对象。
🌐 Like array.map, but works with any iterable.
reduce(iterable, reducer, initialValue)
来源 · 返回由给定 reducer 函数定义的归约值,该函数会对 iterable 中的每个值重复调用,并传入当前的归约值和下一个值。
d3.reduce(new Set([0, 2, 3, 4]), (p, v) => p + v, 0) // 9像 array.reduce,但适用于任何可迭代对象。
🌐 Like array.reduce, but works with any iterable.