joshk132
joshk132

Reputation: 1093

Remove first element in an array inside another array

I have an array of arrays that gets returned from a mongo query. I want to take and remove the first item/element in each array. Here is my node route

Route partial

let queries = [
    User.find({"companyID":req.user.companyID}, (err, foundUsers) => {
        if (err) throw err;
    }),
];
Promise.all(queries)
.then(results => {
    res.render('hr/employees', {header: 'EMPLOYEES', users: results[0]});
}).catch( err => {
    req.flash('error', err);
    res.render('hr/employees', {header: 'EMPLOYEES'});
});

Sample arrays

What I have now

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

What I want

[[2, 3], [5,6], [8,9]]

Upvotes: 1

Views: 126

Answers (4)

Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6289

Something like this should do the job,

const arrOfArrays = []; // get value from response
// remove first element from all arrays safely
const newArr = arrOfArrays.map(arr => (arr && arr.length) ? arr.shift() : arr); 

Edit: As @rghossi pointed out, the above snippet should return an array of first elements. So the right way to do it would be,

const arrOfArrays = []; // get value from response
// remove first element from all arrays safely
const newArr = arrOfArrays.map(arr => (arr && arr.length) ? arr.slice(1) : arr); 

Upvotes: 1

rghossi
rghossi

Reputation: 598

Let's suppose results is an array of arrays. Use slice inside a map to remove the first element and return the desired array.

Promise
  .all(queries)
  .then(results => (results.map(result => (result.slice(1)))))
  .then(adaptedResults => res.render('hr/employees', { header: 'EMPLOYEES', users: adaptedResults[0] });

EDIT: Using the values you have provided.

console.log([[1, 2, 3], [4, 5, 6], [7, 8, 9]].map(arr => (arr.slice(1))))

Upvotes: 1

Ammar Ali
Ammar Ali

Reputation: 690

You can use slice() and shift() method to that easily

for (i = 0; i < results.length; i++) {
    results[i].slice(1);//OR you can use results[i].shift()
}

Or you can modify your code like:

Promise.all(queries)
.then(results => (results.map(result => (result.shift())) {
    //OR you can use result.slice()
    //Your code here
});

It will remove all first element in an array of arrays.

Upvotes: 0

user835611
user835611

Reputation: 2366

Sounds like Array.prototype.shift() is what you're looking for: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Upvotes: 0

Related Questions