我试图编写一个函数,它接受数组作为参数,并在特定条件下过滤这个数组。我稍后会解释这个情况。例如,我有这样的数组:
const arr = [
[1, 1, 20],
[2, 1, 15],
[3, 1.5, 15],
[4, 1, 15],
[5, 1, 20],
[6, 1.5, 15],
[7, 1, 25],
[8, 1, 15],
[9, 0, 15],
[10, 0, 15],
[11, 0, 15],
]
还有条件。我想用第三列的值过滤它,但前提是它在一个序列中至少是三个。函数应该接受两个参数(如果需要的话更多):value和数组,例如
const filterByValue = (array, val) => { //definition
return filtredArr
}
const newArr =filterByValue(数组,15),现在newArr应该等于:
[
[2, 1, 15],
[3, 1.5, 15],
[4, 1, 15],
[8, 1, 15],
[9, 0, 15],
[10, 0, 15],
[11, 0, 15],
]
现在我只做了:
const filterByValue = (arr, value) => {
const newArr = arr.filter((elem, index) => elem[2] === value)
return newArr
}
但是这个函数会返回
[
[2, 1, 15],
[3, 1.5, 15],
[4, 1, 15],
[6, 1.5, 15],
[8, 1, 15],
[9, 0, 15],
[10, 0, 15],
[11, 0, 15],
]
不应该有6,1.5,15,我不知道如何才能只返回至少包含三个内部数组的数组的片段。也许你们有什么想法吗?
编辑更多解释
对于我来说,这个序列意味着我只想输出在第三个值中包含一个设置值的内部数组(函数中的值参数),但是它们也有相互跟随的内部数组(至少三个)。让我们假设函数接受arr ( my中的第一个数组)和value = 15。第一个内部数组包含20作为第三个值,因此它会掉下来。第二个是好的,第三个也是第四个,在这种情况下应该返回2,3,4内部董事会(因为他们接连三个)。那么第五个值是20,第六个值是15,但是下一个(第七个)值又是25,所以函数不应该考虑第六个表(因为它后面没有至少两个具有15值的表)。在表8,9,10,11中,我们有15的值,这是四个表(即至少三个)。因此,函数应该返回一个数组,其中包含以下表2、3、4和8、9、10、11。第六个数组包含值15,但后面不包括另外两个具有此值的数组。预期的产出是我职位上的第二个董事会。
发布于 2020-06-02 09:01:43
const filterByValue = (arr,value) => {
let newArray = [];
let cache = [];
arr.forEach(elem => {
if (elem[2] === value) {
cache.push(elem);
} else {
if (cache.length >= 3) {
newArray = newArray.concat(cache);
}
cache = [];
}
});
if (cache.length >= 3) {
newArray = newArray.concat(cache);
}
return newArray;
}
发布于 2020-06-02 09:01:56
您可以对索引进行闭包,并检查这些值是否为3。
const
array = [[1, 1, 20], [2, 1, 15], [3, 1.5, 15], [4, 1, 15], [5, 1, 20], [6, 1.5, 15], [7, 1, 25], [8, 1, 15], [9, 0, 15], [10, 0, 15], [11, 0, 15]],
value = 15,
result = array.filter(
(index => ({ 2: v }, i, a) => {
if (v !== value) return false;
if (index === i || a[i + 1][2] === value && a[i + 2][2] === value) {
index = i + 1;
return true;
}
})
(-1)
);
console.log(result);
发布于 2020-06-02 10:42:21
根据是否匹配值,尝试使用filter
和条件。
const arr = [
[1, 1, 20],
[2, 1, 15],
[3, 1.5, 15],
[4, 1, 15],
[5, 1, 20],
[6, 1.5, 15],
[7, 1, 25],
[8, 1, 15],
[9, 0, 15],
[10, 0, 15],
[11, 0, 15],
];
const filterByValue = (array, val) =>
array.filter((ar, i, items) => {
if (ar[2] !== val) {
return true;
} else {
return items[i - 1][2] === val || items[i + 1][2] === val;
}
});
console.log(filterByValue(arr, 15));
https://stackoverflow.com/questions/62148045
复制相似问题