22 Utility Functions To Ace Your JavaScript Coding Interview


22 Utility Functions To Ace Your JavaScript Coding Interview


JavaScript Coding Assessment Cheatsheet 2021

One type of JavaScript coding interview question you might encounter will involve you writing 1–2 lines of code for a given question. These questions are usually simple enough to answer in 5 minutes, but sometimes we struggle with them due to the pressure of the interview. These functions will help to prepare for your JavaScript Interviews in 2021.

To reduce the pressure at times let’s get prepared ahead of time!

Photo by Patrick Perkins on Unsplash

1. Remove Duplicates from an Array

Arrays : these are some handy methods that we can use to remove duplicates from an array.

Using lodash

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let arrayuniq = _.uniq(array);
//[2, 1, 5, 6, 7, 8, 9, 10]

Using the filter

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let list = array.filter((x, i, a) => a.indexOf(x) == i);
//[2, 1, 5, 6, 7, 8, 9, 10]

Using Set

let array = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let setuniq = [...new Set(array)];
//[2, 1, 5, 6, 7, 8, 9, 10]

Removing duplicate values with reduce

You can also remove duplicate values of an array with reduce(). But since you want to return an array instead of a number, you need to define the initial value as an empty array. Take a look at the following code example:

let myScores = [1, 2, 7, 2, 5, 8, 7];

let noDupeArray = myScores.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

The accumulator starts as an empty array. If the current value is not yet included in the accumulator, you push the value into it.

The reduce method can return any data type that you want to return, as long as it’s a single value (a string, a number, an array or an object, or even boolean).

2. Remove Duplicates from Array of Objects

  • Arrays of Objects: these are some handy methods that we can use to remove duplicates from an array of objects.
  1. Using lodash
let users = [
  { id: 1, name: 'ted' },
  { id: 1, name: 'bob' },
  { id: 3, name: 'sara' },
  { id: 4, name: 'test' },
  { id: 4, name: 'test' },
  { id: 5, name: 'abc' },
];
let uniqueUsersByID = _.uniqBy(users, 'id');
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]

We can check unique data with multiple properties with this code.

const uniquewithMultipleProperties = _.uniqWith(
  users,
  (a, b) => a.id === b.id || a.name === b.name,
);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]
  1. Using a filter
let filteruniquebyID = users.filter((v, i, a) => a.findIndex((t) => t.id === v.id) === i);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]

We can check unique data with multiple properties with this code.

let filteruniquebyIDName = users.filter(
  (v, i, a) => a.findIndex((t) => t.id === v.id || t.name === v.name) === i,
);
//[{"id":1,"name":"ted"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]
  1. Using Set
var set1 = Array.from(users.reduce((m, t) => m.set(t.id, t), new Map()).values());
//[{"id":1,"name":"bob"},{"id":3,"name":"sara"},{"id":4,"name":"test"},{"id":5,"name":"abc"}]

You can check stackblitz here.

https://stackblitz.com/edit/remove-duplicates-arrayofobjects

3. Find an item in Array

  • below are some methods to find an item in the array
  1. includes: this method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

console.log(redFruits.includes('apple')); // returns true

Array.includes 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true, 否则返回 false.

  1. every: this method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
let testevery1 = array.every((val) => val > 3); //false
  1. some: this method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let testsome1 = array.some((val) => val > 3); //true
  1. lodash includes: checks if value is in collection .Returns true if value is found, else false .
let lodashtest9 = _.includes(array, 1); // truelet lodashtest10 =_.includes(array, 3, 2); // false
  1. findIndex: this method returns the index of the first element in the array that satisfies the provided testing function . Otherwise, it returns -1 , indicating that no element passed the test.
let testindex = array.findIndex((val) => val > 1);
//0
  1. find: this method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined are returned.
let testfind = array.find((el) => el > 2);
//5

7. filter: this method creates a new array with all elements that pass the test implemented by the provided function.

let testfilter1 = array.filter((val) => val > 3);
//[5, 6, 7, 8, 9, 9, 10]
  1. map: this method creates a new array populated with the results of calling a provided function on every element in the calling array.
let val = [];
array.map((item) => {
  if (item >= 3) val.push(item);
});
//[5, 6, 7, 8, 9, 9, 10]

You can check stackblitz here.

https://stackblitz.com/edit/find-item-array

4. Find an item in the Array of Objects

  • these are the methods that can be used to find an item in the array of objects.
  1. every: this method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
let testevery2 = users.every((val) => val.id > 3);
//false
  1. some: this method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let testsome2 = users.some((val) => val.id > 3); //true
  1. lodash includes: checks if value is in collection .Returns true if value is found, else false .
let lodashtest11 = _.includes({ a: 1, b: 2 }, 1);
//true
let lodashtest12 = _.includes('abcd', 'bc');
//true
  1. findIndex: this method returns the index of the first element in the array that satisfies the provided testing function . Otherwise, it returns -1 , indicating that no element passed the test.
let testindex2 = users.findIndex((val) => val.id > 1);
//3
  1. find: this method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined are returned.
let testfind2 = users.find((el) => el.id > 2);
//{"id":3,"name":"sara"}

6. filter: this method creates a new array with all elements that pass the test implemented by the provided function.

let testfilter2 = users.filter((val) => val.id > 3);
  1. map: this method creates a new array populated with the results of calling a provided function on every element in the calling array.
let val2 = [];
users.map((item) => {
  if (item.id >= 3) val2.push(item);
});

You can check stackblitz here.

https://stackblitz.com/edit/find-item-array

5. Sort Array items

Arrays can be sort using the sort method.

The sort() method sorts the elements of an array _in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

6. Sort Array Of Objects with specific properties

  • these are the methods that can be used to sort an array of objects using specific property from objects.

1. Simple Sort: this method sorts the elements of an array in place and returns the sorted array.

let data = [
  {
    id: '3',
    city: 'toronto',
    state: 'TR',
    zip: '75201',
    price: '123451',
  },
  {
    id: '1',
    city: 'anand',
    state: 'AN',
    zip: '94210',
    price: '345678',
  },
  {
    id: '5',
    city: 'sudbury',
    state: 'SB',
    zip: '00110',
    price: '789045',
  },
];
let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id)));
console.log('sort test 2 ', sorttest2);
//output
[
  {
    id: '1',
    city: 'anand',
    state: 'AN',
    zip: '94210',
    price: '345678',
  },
  {
    id: '3',
    city: 'toronto',
    state: 'TR',
    zip: '75201',
    price: '123451',
  },
  {
    id: '5',
    city: 'sudbury',
    state: 'SB',
    zip: '00110',
    price: '789045',
  },
];

2. localCompare: this method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

let sorttest2 = data.sort((a, b) => (a.id < b.id ? -1 : Number(a.id > b.id))); //output
[
  {
    id: '1',
    city: 'anand',
    state: 'AN',
    zip: '94210',
    price: '345678',
  },
  {
    id: '3',
    city: 'toronto',
    state: 'TR',
    zip: '75201',
    price: '123451',
  },
  {
    id: '5',
    city: 'sudbury',
    state: 'SB',
    zip: '00110',
    price: '789045',
  },
];

3. Sort with multiple fields

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

let sorttest4 = data.sort(function (left, right) {
  var city_order = left.city.localeCompare(right.city);
  var price_order = parseInt(left.price) - parseInt(right.price);
  return city_order || -price_order;
});
//output
[
  {
    id: '1',
    city: 'anand',
    state: 'AN',
    zip: '94210',
    price: '345678',
  },
  {
    id: '5',
    city: 'sudbury',
    state: 'SB',
    zip: '00110',
    price: '789045',
  },
  {
    id: '3',
    city: 'toronto',
    state: 'TR',
    zip: '75201',
    price: '123451',
  },
];

4. Lodash sortBy: Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iterate.

let sorttest6 = .sortBy(data, ["id", "city"]);
//output
[{
    "id": "1",
    "city": "anand",
    "state": "AN",
    "zip": "94210",
    "price": "345678"
}, {
    "id": "3",
    "city": "toronto",
    "state": "TR",
    "zip": "75201",
    "price": "123451"
}, {
    "id": "5",
    "city": "sudbury",
    "state": "SB",
    "zip": "00110",
    "price": "789045"
}]

7. Sort Array of Dates

1. Using Sort

let isDescending = false; //set to true for Descending
let dates = ['1/7/2021', '1/6/2021', '8/18/2020', '8/6/2020'];
let sorteddates = dates.sort((a, b) =>
  isDescending
    ? new Date(b).getTime() - new Date(a).getTime()
    : new Date(a).getTime() - new Date(b).getTime(),
);
console.log(sorteddates);
//["8/6/2020", "8/18/2020", "1/6/2021", "1/7/2021"]

2. Using Lodash

let arr = [
  { name: 'test1', date: '1/7/2021' },
  { name: 'test2', date: '1/6/2021' },
  { name: 'test3', date: '1/5/2020' },
];
arr = _.sortBy(arr, function (dateObj) {
  return new Date(dateObj.date);
});
console.log('sort date', arr);
//[{"name":"test3","date":"1/5/2020"},{"name":"test2","date":"1/6/2021"},{"name":"test1","date":"1/7/2021"}]

3. Using Lodash (sort by month and year)

let yearAndMonth = [
  { year: 2016, month: 'FEBRUARY' },
  { year: 2015, month: 'MARCH' },
  { year: 2021, month: 'JANUARY' },
  { year: 2021, month: 'FEBRUARY' },
];

let value = _.sortBy(yearAndMonth, (a) => new Date(1 + a.month + a.year));
console.log('Sorted Result: ', value);
//[{"year":2015,"month":"MARCH"},{"year":2016,"month":"FEBRUARY"},{"year":2021,"month":"JANUARY"},{"year":2021,"month":"FEBRUARY"}]

You can check stackblitz here.

https://stackblitz.com/edit/sort-array

8. Remove an item from an Array

1. pop: this method removes the last element from an array and returns that element. This method changes the length of the array.

let arraypoptest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testpop = arraypoptest.pop();
console.log('array pop', testpop, '-', arraypoptest);
//10 - [2, 1, 2, 5, 6, 7, 8, 9, 9];

2. shift: this method removes the first element from an array and returns that removed element. This method changes the length of the array.

let arrayshifttest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testshift = arrayshifttest.shift();
console.log('array shift', testshift, '-', arrayshifttest);
//2 - [1, 2, 5, 6, 7, 8, 9, 9, 10]

3. slice: this method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.

let arrayslicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testslice = arrayslicetest.slice(0, 3);
console.log('array slice', testslice, arrayslicetest);
//not changed original array
//[2, 1, 2] - [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]

4. splice: this method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place .

let arraysplicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testsplice = arrayslicetest.splice(0, 3);
//[2, 1, 2]

5. filter: this method creates a new array with all elements that pass the test implemented by the provided function.

arrays:

let testarr = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let testarr2 = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let filtered = testarr.filter(function (value, index, arr) {
  return value > 5;
});
let filtered2 = testarr2.filter((item) => item !== 2);
console.log('filter example 1', filtered);
//[6, 7, 8, 9, 9, 10]
console.log('filter example 2', filtered2);
//[1, 5, 6, 7, 8, 9, 9, 10]
  • filter with multiple values removal:
let forDeletion = [2, 3, 5];
let mularr = [1, 2, 3, 4, 5, 3];
mularr = mularr.filter((item) => !forDeletion.includes(item));
console.log('multiple value deletion with filter', mularr);
//[1, 4]

6. delete operator: The JavaScript delete removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

let ar = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
delete ar[4];
// delete element with index 4
console.log(ar);
//[2, 1, 2, 5, undefined, 7, 8, 9, 9, 10]

7. lodash remove: _remove removes all elements from array that predicate returns truthy for and returns an array of the removed elements.

let arrlodashtest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
let evens = .remove(arrlodashtest, function(n) {
 return n % 2 == 0;
});
console.log("lodash remove array", arrlodashtest);
//[1, 5, 7, 9, 9]

9. Remove an item from the Array of Objects

1. pop: this method removes the last element from an array and returns that element. This method changes the length of the array.

let users1 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let testpop1 = users1.pop();
console.log('array of objects pop', JSON.stringify(testpop1), '-', JSON.stringify(users1));
//{"id":4,"name":"sara"} - [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]

2. shift: this method removes the first element from an array and returns that removed element. This method changes the length of the array.

let users2 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let testshift1 = users2.shift();
console.log('array of objects shift', JSON.stringify(testshift1), '-', JSON.stringify(users2));
//{"id":1,"name":"ted"} - [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]

3. slice: this method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.

let users3 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let testslice1 = users3.slice(0, 3);
console.log('array of objects slice', JSON.stringify(testslice1));
//not changed original array
//[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]

4. splice: this method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place .

let users4 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let testspice1 = users3.splice(0, 3);
console.log('array of objects splice', JSON.stringify(testsplice));
//[{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]

5. filter: this method creates a new array with all elements that pass the test implemented by the provided function.

let users7 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let filterObj = users7.filter((item) => item.id !== 2);
console.log('filter example array of objects', filterObj);
//[{"id":1,"name":"ted"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]

6. lodash remove: _remove removes all elements from array that predicate returns truthy for and returns an array of the removed elements.

let users8 = [
  { id: 1, name: 'ted' },
  { id: 2, name: 'mike' },
  { id: 3, name: 'bob' },
  { id: 4, name: 'sara' },
];
let evensObj = _.remove(users8, function (n) {
  return n.id % 2 == 0;
});
console.log('lodash remove array of object', JSON.stringify(evensObj));
//[{"id":2,"name":"mike"},{"id":4,"name":"sara"}]

You can check stackblitz here.

https://stackblitz.com/edit/array-remove-item

10. Find Number of Characters From Given String in Array

1. String match method

The match() method retrieves the result of matching a string against a regular expression . (source: MDN )

const test1 = ('atit patel'.match(/a/g) || []).length;
console.log(test1); //2

2. String split method

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.

const test2 = 'atit patel'.split('a').length - 1;
console.log(test2); //2

3. indexOf method

The indexOf() method returns the index within the calling Stringobject of the first occurrence of the specified value, starting the search at fromIndex . Returns -1 if the value is not found.

let stringsearch = 'a',
  str = 'atit patel';
for (
  var count = -1, index = -2;
  index != -1;
  count++, index = str.indexOf(stringsearch, index + 1)
);
console.log(count); //2

4. filter method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const mainStr = 'atit patel';
const test3 = [...mainStr].filter((l) => l === 'a').length;
console.log(test3); //2

5. reduce method

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const mainStr1 = 'atit patel';
const test4 = [...mainStr1].reduce((a, c) => (c === 'a' ? ++a : a), 0);
console.log(test4); //2

11. Find Number of Occurrences of each Character From Given String in Array

1. We can add reduce method which we can return object after iterations

let s = 'atit patel';
let test5 = [...s].reduce((a, e) => {
  a[e] = a[e] ? a[e] + 1 : 1;
  return a;
}, {});
console.log(test5); //{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}

2. It is the same as method 6 with having OR operator

let test6 = [...s].reduce((res, char) => ((res[char] = (res[char] || 0) + 1), res), {});
console.log(test6); //{a: 2,e: 1,i: 1,l: 1,p: 1,t: 3}

You can play with stackblitz here.

https://stackblitz.com/edit/numberofoccurance-string

12. Rename Object Properties in Array of Objects

1. Using Map: this method creates a new array populated with the results of calling a provided function on every element in the calling array.

let countries = [
  { id: 1, name: 'india' },
  { id: 2, name: 'canada' },
  { id: 3, name: 'america' },
];
const transformed = countries.map(({ id, name }) => ({
  label: id,
  value: name,
}));
console.log('1', JSON.stringify(transformed));
[
  { label: 1, value: 'india' },
  { label: 2, value: 'canada' },
  { label: 3, value: 'america' },
];

2. Using a map with arguments

const transformed2 = countries.map(({ id: label, name: value }) => ({
  label,
  value,
}));
console.log('2', JSON.stringify(transformed2));
[
  { label: 1, value: 'india' },
  { label: 2, value: 'canada' },
  { label: 3, value: 'america' },
];

3. Using lodash: _.mapKeys method creates an object with the same values as object and keys generated by running each own enumerable string keyed property of object thru iteratee .

const test1 = _.mapKeys({ a: 1, b: 2 }, function (value, key) {
  return key + value;
});
console.log('3', test1);
//_{a1: 1, b2: 2}

What if we want to rename Object keys? Let’s check out the solution for that.

4. Using lodash for objects for values

var users = {
  atit: { user: 'atit', age: 40 },
  mahesh: { user: 'mahesh', age: 15 },
};
const test2 = _.mapValues(users, function (o) {
  return o.age;
});
console.log('4', test2);
//_{atit: 40, mahesh: 15}_
//shorthand
const test3 = _.mapValues(users, 'age');
console.log('5', test3);
//_{atit: 40, mahesh: 15}_

5. Using Object destructuring: The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

const rename = ({ id: a_b_c, ...rest }) => ({ a_b_c, ...rest });
console.log(rename({ id: 1, val: 2 }));
//{a_b_c: 1, val: 2}

you can play with stackblitz here.

https://stackblitz.com/edit/rename-object-keys

13. How to merge two arrays and create a new array?

This can be achieved simply by using the spread operator.

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e'];
var merged = [...arr1, ...arr2];
console.log(merged);

14. A sum of an array of numbers

  1. reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.
console.log([1, 2, 3, 4].reduce((a, b) => a + b, 0));
console.log([].reduce((a, b) => a + b, 0)); //10

2. Using Lodash

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10

Let’s check some of the complex scenarios which can be helpful in Coding Assessments

15. Compare two arrays of objects, remove duplicates, merge objects based on property

We do get a requirement to compare two different arrays of objects and want to merge both objects if they match specific property values. It can be achieved using the filter method.

The filter() method creates a new array with all elements that pass the test implemented by the provided function. (source: MDN )

Let’s create test data.

let array1 = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
];
let array2 = [
  { id: '53', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
  { id: '52', active: 'a', value: 13 },
];

Let’s create functions.

let res = array2.filter((val) => array1.some(({ value }) => val.value === value));

console.log('1', JSON.stringify(res));

// [
//   { id: '53', active: 'a', value: 10 },
//   { id: '51', active: 'a', value: 11 },
// ];

16. Compare two arrays of objects, merge and update values (assuming array 3,4 shares same ID)

We do get requirements sometimes to merge the two different with new property values. We can create a new set of arrays of objects using the map and we can use the find method to match the specific property before updating the new value.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined are returned. (source: MDN )

Let’s create the test data.

let array3 = [
  { id: '50', active: 'a', value: 12 },
  { id: '51', active: 'a', value: 15 },
];
let array4 = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
  { id: '52', active: 'a', value: 13 },
];

Let’s create functions.

let arr = [];
array3.map((id) =>
  arr.push({
    id: id.id,
    newValue: array4.find((o) => o.id === id.id).value + 2,
  }),
);
console.log('2', JSON.stringify(arr));
// [
//   { id: '50', newValue: 12 },
//   { id: '51', newValue: 13 },
// ];

17. Compare arrays of objects and find unique objects

If we want to compare two arrays of objects and check which are the unique objects from them, we can use a filter to achieve these functions.

Let’s create test data.

const array5 = [
  { id: '50', active: 'a', value: 12 },
  { id: '51', active: 'a', value: 15 },
];
const array6 = [
  { id: '50', active: 'a', value: 12 },
  { id: '51', active: 'a', value: 15 },
  { id: '52', active: 'a', value: 13 },
];

Let’s create functions

const ids = array5.map((e) => e.id);
let filtered = array6.filter((e) => ids.includes(e.id));
console.log('3', JSON.stringify(filtered));

// [
//   { id: '50', active: 'a', value: 12 },
//   { id: '51', active: 'a', value: 15 },
// ];

18. Compare and update property based on matched values

When we want to compare two arrays of objects and update the specific property based on the matched values we can use these functions.

Let’s create test data

const array7 = [
  { id: '50', active: 'a', value: 12 },
  { id: '51', active: 'a', value: 15 },
];
const array8 = [{ id: '50', active: 'a', value: 12 }];

Let’s create functions

const idSet = new Set(array8.map((o) => o.id));
const res1 = array7.map((o) => ({
  ...o,
  value: idSet.has(o.id) ? '0' : o.value,
}));
console.log('4', JSON.stringify(res1));
//[{"id":"50","active":"a","value":"0"},{"id":"51","active":"a","value":15}]

19. Compare two arrays objects and get the differences

When we want to compare two different arrays of objects and get are differences between them we can use these functions.

Let’s create test data

let a = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
];
let b = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
  { id: '52', active: 'a', value: 13 },
];

Let’s create functions

let valuesArray1 = a.reduce(function (a, c) {
  a[c.value] = c.value;
  return a;
}, {});
let valuesArray2 = b.reduce(function (a, c) {
  a[c.value] = c.value;
  return a;
}, {});
var result = a
  .filter(function (c) {
    return !valuesArray2[c.value];
  })
  .concat(
    b.filter(function (c) {
      return !valuesArray1[c.value];
    }),
  );
console.log('5', result);
//[{"id":"52","active":"a","value":13}]//shorthandlet ab = b.filter(o => !a.find(o2 => o.id === o2.id));console.log("6", ab);

20. Compare two arrays of objects merge and remove duplicates

If we get requirements to compare two arrays of objects and remove the duplicates from them and merge both the arrays we can use this method.

Let’s create test data

let arr1 = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
];
let arr2 = [
  { id: '50', active: 'a', value: 10 },
  { id: '51', active: 'a', value: 11 },
  { id: '52', active: 'a', value: 13 },
];

Let’s create functions

const arr1IDs = new Set(arr1.map(({ id }) => id));
const combined = [...arr1, ...arr2.filter(({ id }) => !arr1IDs.has(id))];
console.log(JSON.stringify(combined));
//[{"id":"50","active":"a","value":10},{"id":"51","active":"a","value":11},{"id":"52","active":"a","value":13}]
  • Using lodash

Lodash supports _differenceBy and _differenceWith methods to find the difference between two arrays.

let lodashtest1 = [{ id: '50' }, { id: '51' }];
let lodashtest2 = [{ id: '50' }, { id: '51' }, { id: '52' }];
let lodashresult = _.differenceBy(lodashtest2, lodashtest1, 'id');
console.log('7', JSON.stringify(lodashresult));
//[{"id":"52"}]
let dif = _.differenceWith(lodashtest2, lodashtest1, .isEqual);
console.log("8",JSON.stringify(dif));
//[{"id":"52"}]

21. Compare objects and find unique values

When we do work with nested objects sometimes it is difficult to figure out how we can iterate and compare both nested objects and get some unique objects among them. We can use Object.keys and Object.values methods for the iterations.

Let’s create test data

let obj1 = { val1: 'test', stream: { prop1: false, prop2: true } };
let obj2 = { val1: 'test', stream: { prop1: true, prop2: true } };
interface Data {
  stream: { [key: string]: boolean };
}

Let’s create functions:

function objFilter(objA: Data, objB: Data): Data {
  let out: Data = { stream: {} };
  Object.keys(objA.stream).filter((value, idx) =>
    Object.values(objA.stream)[idx] === Object.values(objB.stream)[idx]
      ? (out.stream[value] = Object.values(objA.stream)[idx])
      : false,
  );
  return out;
}
console.log(JSON.stringify(objFilter(obj1, obj2))); //prop2
//{"stream":{"prop2":true}}

If you would like to play with stackbliz check out here: https://stackblitz.com/edit/compare-objects-javascript

22. How to Handle Multiple Service Calls Inside a Loop

  1. If we don’t want to wait for all the service calls to finish
let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }];
async function getDetails(values) {
  for (const data of values) {
    const result = await axios.get(`serviceURL/${data.id}`);
    const newData = result.data;
    this.updateDetails(newData);
    console.log(this.response);
  }
}
function updateDetails(data) {
  this.response.push(data);
}
getDetails(data); //call service to get data
  1. If we want to wait until all service calls done

we can use promise.all to wait until all promises have been resolved.

The Promise.all() the method takes an iterable of promises as an input and returns a single Promise that resolves to an array of the results of the input promises. (source: MDN )

let data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }];
async function getDetails(values) {
  const dataPromises = values.map((entry) => {
    return axios.get(`serviceURL/${entry.id}`);
  });
  const resultData = await Promise.all(dataPromises);
  resultData.forEach((res: any) => {
    this.updateDetails(res.data);
  });
  console.log(this.response);
}
function updateDetails(data) {
  this.response.push(data);
}
getDetails(data); //call service to get data

文章作者: Atit
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Atit !
  目录