new array from existing array using specific elements

I am still learning, I have tried to find a solution for this but I think I am missing/overlooked something and can’t seem to crack it,

I am creating a node .js file and inside,

I have this function,

var goingTomorrow = rows.filter(ifDateTomorrow);
        function ifDateTomorrow(value) {
            return value[5] === dateTomorrow;
        }

Which returns all rows where element 5 in the array === tomorrows date to the variable goingTomorrow, this works.

Then I have,

var sum = 0;
        for (var x = 0; x < goingTomorrow.length; x++) {
            sum += + goingTomorrow[x][6];
            }

console.log(goingTomorrow.length + ' Bookings: ' + sum + ' pax total for tomorrow'); 

Which calculates the total people for the day by adding all elements in the 5th index to return a total. Also works.

But now I would like to return a new array with only specific elements/indexes to be sent in an email (so all the fields aren’t needed).

I use, goingTomorrow to run the code. goingTomorrow currently outputs:

1,John,w,tourname,2018-08-14,2018-08-14,3,820467370,test address,AS,0,[email protected],0,6,James,M,tourname,2018-08-05,2018-08-14,2,54546456,test address,AS,0,[email protected],0,

But in the email but I would like to choose the specific elements to output as well as output into a array with each result on a new line.

This is what I want to have output,

John,w,2018-08-14,3,820467370,test address,[email protected], 
James,M,2018-08-14,2,54546456,test address,[email protected],

I have tried foreach, map, reduce and newArray to little success.

So, how do I create a new array from goingTomorrow with the specific elements I want. What am I missing? Thank you

Answer

You could use a destructuring assignment for the wanted indices and map a new array.

var array = [[1, 'John', 'w', 'tourname', '2018-08-14', '2018-08-14', 3, '820467370', 'test address', 'AS', 0, '[email protected]', 0], [6, 'James', 'M', 'tourname', '2018-08-05', '2018-08-14', 2, '54546456', 'test address', 'AS', 0, '[email protected]', 0]],
    result = array.map(({ 1: name, 2: gender, 4: date, 7: number, 11: email }) =>
        [name, gender, date, number, email]);

console.log(result);
document.body.innerHTML += result.join('<br>');

Leave a Reply

Your email address will not be published. Required fields are marked *