I have 2 arrays
var array1 = ["1", "2", "3", "4", "5", "6"]
and
var array2 = [
{ offId: "4", offname: "four" },
{ offId: "9", offname: "nine" },
{ offId: "15", offname: "fifteen" },
{ offid: "3", offname: "three" },
{ offId: "1", offname: "one" },
{ offId: "0", offname: "zero" },
{ offId: "8", offname: "eight" },
{ offId: "10", offname: "ten" },
]
i need to compare two arrays with the values of offId and the resulted array should be
var array3 = [
{ offId: "1", offname: "one" },
{ offId: "2", offname: "" },
{ offId: "3", offname: "three" },
{ offId: "4", offname: "four" },
{ offId: "5", offname: "" },
{ offId: "6", offname: "" },
]
How could i achieve this(length of the array may be same or different)
You can use
Array.reduce
to createarray3
fromarray1
&array2
.Here are the steps :
acc
(accumulated array) will contain the empty array initially.Array.find
to check if thecurr
(current variable) is in array2.Array.find
will return the object ifa.offId
matches thecurr
value.obj
is found, push theobj
inacc
(accumulated array){offId: curr, offname: ''}
in the arrayYou could take a
Map
and use either the stored object or a new object.The easiest way would be to simply
filter()
the second array:That will loop through every element in
array2
and only leave the ones which have theiroffId
inarray1
.If you need it sorted, then just add a sort to the end of that:
If you need to sort it numerically (i.e., you want 2 before 10), then you'll need to cast the values of those, but then you can just subtract them: