1

I am having 2 array lists from which i am finding the difference.

arr1 = ['Sam','Annie', 'Margorie', 'Ester', 'John'];
arr2 = ['Bill', 'Sally', 'Sam', 'Annie', 'Suman', 'Margorie', 'Ester', 'Pierre', 'John'];

var diff = arr2.filter(x => !arr1.includes(x));

console.log(diff) //result....diff = ['Bill', 'Sally', 'Suman', 'Pierre']

What i want to do is to modify the above Filter Arrow function to add 'New' for each item' so that the resultant array becomes:

//diff = [['Bill', 'New'] , ['Sally', 'New'] , ['Suman', 'New'] , ['Pierre' , 'New']]

I can do this separately using a Map Arrow function like this:

diff = diff.map(x => [x,'New']);
  • But i want to club both these functions together. Is that possible?

  • Also, when i try to append this array to the last row of the sheet, the last row shows 'Object@xxx' instead of the actual values.

e.g.

Sht.appendRow(diff);

What am i doing wrong?

1 Answer 1

2

To combine map/filter, Use a simple for-loop/if or reduce:

arr1 = ['Sam','Annie', 'Margorie', 'Ester', 'John'];
arr2 = ['Bill', 'Sally', 'Sam', 'Annie', 'Suman', 'Margorie', 'Ester', 'Pierre', 'John'];

const diff = arr2.reduce((diff,x) => !arr1.includes(x) ? [...diff , [x, "New"]] : diff, [] );

console.log(diff) //result....diff = ['Bill', 'Sally', 'Suman', 'Pierre']

Sheet#appendRow only accepts a 1D(1-dimensional) array. Use range.setValues() if you want to append a 2D array.

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

4 Comments

Thanks. Just on a side note, can this be rewritten as normal javascript instead of using Arrow functions? I am still grappling with Arrow functions.
@sifar const diff = arr2.reduce(function(diff,x) { return !arr1.includes(x) ? [...diff , [x, "New"]] : diff}, [] ); or more elaborately const diff = arr2.reduce(function(diff,x) { if (!arr1.includes(x))return diff.concat([x, "New"]); return diff}, [] );
Excellent! But is there a reason for using Const instead of Var? And from a speed performance perspective, which should be faster for large ranges?
@sifar const or let is preferable due to scope restrictions and therefore less error-prone. var should generally be avoided. JavaScript tag info page has excellent resources.

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.