0

I need to delete some columns in a 2d array. The list is named as hiddenCols

var array = [
  ["a", "b", "c"],
  ["a", "b", "c"],
  ["a", "b", "c"]
]

hiddenCols = [3, 1] // these are pos and not indexes
for (var j = 0; j < array.length; j++) {
  for (var i = 0; i < hiddenCols.length; i++) {

    array[j].splice(hiddenCols[i], hiddenCols[i])
  }
}
console.log(JSON.stringify(array));

The expected result is var array = [["b"],["b"],["b"]];

2
  • for (var j = 0; i < array.length; i++) { the variable j is declared as a loop variable but i is used in the check for termination. Commented Jan 20, 2021 at 13:54
  • The expected result is var array = [["b"],["b"],["b"]]; Commented Jan 20, 2021 at 13:56

2 Answers 2

1

You could do with Arrya#reduce

const arr = [["a", "b", "c"],["a", "b", "c"],["a", "b", "c"]];
const hiddenCols = [3, 1];

let result = arr.reduce((acc, item) => {
  let res = item.filter((_, ind) => hiddenCols.indexOf(ind + 1) == -1);
  acc.push(res)
  return acc;
}, [])

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

No need for reduce() since you're returning an array of the same length simply use map()
@pilchard yes.. but someone already posted. And this also one of the method right then why down-voted
1

Use Array.map() to iterate the rows, and filter the items by checking that the position is not included in hiddenCol:

const arr = [["a", "b", "c"],["a", "b", "c"],["a", "b", "c"]]

const hiddenCols = [3, 1]
const result = arr.map(item =>
  item.filter((_, ind) => !hiddenCols.includes(ind + 1))
)

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.