user8779054
user8779054

Reputation: 183

Remove values from subarrays javascript

Having some difficulty removing the row 0 in all my subarrays

Tried splice as well but can't seem to find a good example that remove values from subarrays.

Arr1

// This is how my main Arr1 looks like
(3) [Array(2), Array(2), ...]
0: (2) ["2021-07-06T00:00:00Z", {…}]
1: (2) ["2021-07-06T00:00:00Z", {…}]
...

// Which will have multiple subarrays when the main array is expanded
0: Array(2)
0: "2021-07-06T00:00:00Z"
1: {type: "meeting", id: "123"}

1: Array(2)
0: "2021-07-06T00:00:00Z"
1: {type: "call", id: "456"}

....

End result - Remove row 0, which is the date & time from each array and combine all of them together

0: {type: "meeting", id: "123"}
1: {type: "call", id: "456"}

Upvotes: 1

Views: 343

Answers (5)

RenaudC5
RenaudC5

Reputation: 3829

I would personnaly recommand using map which here takes for each element in your array, the second element (which is your object)

const arr = [
    ["2021-07-06T00:00:00Z", {type:"meeting",id:"123"}],
    ["2021-08-06T00:00:00Z", {type: "call", id: "456"}],
    ["2021-09-06T00:00:00Z", {type: "zoom", id: "789"}]
];

console.log(arr.map(item => item[1]))

Upvotes: 2

Atharva Sharma
Atharva Sharma

Reputation: 315

Here's how you can do it:

let result = [];
let arr = [
    ["2021-07-06T00:00:00Z", {type:"meeting",id:"123"}],
    ["2021-07-06T00:00:00Z", {type: "call", id: "456"}]
];
result = arr.map((item)=>{
    return item[1];
})
console.log(result);

Upvotes: 1

underscore
underscore

Reputation: 6887

use Map with filter

var a = [[1,2], [3,4]]

console.log(a.map((b) => b.filter((c, i) => i != 0)))

Result

[[2], [4]]

Upvotes: 1

Killian Huyghe
Killian Huyghe

Reputation: 1624

You can use a slice to remove the first element of each subarray. And a flatMap to join all the filtered subarrays into one single array.

Here's how I would do it:

const filteredArray = array.flatMap((subarray) => subarray.slice(1));

Upvotes: 1

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

Since you have nested arrays you will have to combine map and filter. Map to iterate the top level and filter or splice (depending on your logic) - on the sub to remove or filter out items.

topArray.map(subArray => subArray.filter(item => ...))

or

topArray.map(subArray => subArray.splice(start, deleteCount)

If you then want to "flatten" the results you can add .flat() or .flatMap() to the end (depending on your logic)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


If you know that you just want to grab the first item on each sub-array, you can:

topArray.map(subArray => subArray[0])

Upvotes: 2

Related Questions