4 回答
TA贡献1840条经验 获得超5个赞
如果你想要多维数组作为结果
function filteredArray(arr, elem) {
let newArr = [];
for (var i = 0; i < arr.length; i++) {
let subArray=[];
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] !==elem) {
subArray.push(arr[i][j]);
}
}
newArr.push(subArray)
}
return newArr;
}
console.log((filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)));
如果你想要平面阵列作为结果
function filteredArray(arr, elem) {
let newArr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] !==elem) {
newArr.push(arr[i][j]);
}
}
}
return newArr;
}
console.log((filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)));
TA贡献1828条经验 获得超6个赞
不使用filter方法,但如果可以使用map,reduce将简化,可以避免使用索引处理。
const filteredArray = (arr, elem) =>
arr.map((data) =>
data.reduce((acc, cur) => (cur !== elem && acc.push(cur), acc), [])
);
console.log(
filteredArray(
[
[3, 2, 3],
[1, 6, 3],
[3, 13, 26],
[19, 3, 9],
],
3
)
);
如果您需要平面数组,只需更改map为flatMap上面的代码。
const filteredFlatArray = (arr, elem) =>
arr.flatMap((data) =>
data.reduce((acc, cur) => (cur !== elem && acc.push(cur), acc), [])
);
console.log(
filteredFlatArray(
[
[3, 2, 3],
[1, 6, 3],
[3, 13, 26],
[19, 3, 9],
],
3
)
);
TA贡献1797条经验 获得超4个赞
更正
i <= arr.length=>i < arr.length
arr.indexOf(elem)=>arr[i].indexOf(elem)
function filteredArray(arr, elem) {
let newArr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
if (arr[i].indexOf(elem) != -1) {
newArr.push(arr[i]);
}
}
}
return newArr;
}
console.log(JSON.stringify(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)));
TA贡献1783条经验 获得超4个赞
这个逻辑有什么问题?
1-您需要在访问它们之前声明空子数组。
newArr[i] = [];
2-如果未找到 elem,则要推送整个数组(我假设是为了节省时间),请纠正条件或放入其他内容。
newArr.push(arr[i]); but you should use this
newArr[i] = arr[i]; because i created new empty sub arrays.
3-您需要实际使用 j 来遍历子数组。
newArr[i].push(arr[i][j]);
4-已经回答,但你需要检查你没有超出数组。
i < arr.length j < arr[i].length
5-您缺少极端情况。
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 5, 9], [3, 3, 3]], 3) );
function filteredArray(arr, elem) {
const newArr = [];
let skip = 0;
for (var i = 0; i < arr.length; i++) {
newArr[i] = [];
skip = arr[i].indexOf(elem);
for (var j = 0; j < arr[i].length; j++) {
if (skip !== -1) {
if (arr[i][j] !== elem) {
newArr[i].push(arr[i][j]);
}
} else {
newArr[i] = arr[i];
break;
}
}
}
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 5, 9], [3, 3, 3]], 3));
添加回答
举报