let obj =[
{
"SID": 123,
"EMPLOYEE_NAME": "Test123",
"EMPLOYEE_ID": 1
},
{
"SID": 543,
"EMPLOYEE_NAME": "Test1543",
"EMPLOYEE_ID": 2
},
{
"SID": 454,
"EMPLOYEE_NAME": "Test1454",
"EMPLOYEE_ID": 3
},
{
"SID": 789,
"EMPLOYEE_NAME": "Test1789",
"EMPLOYEE_ID": 4
},
{
"SID": 999,
"EMPLOYEE_NAME": "Test1999",
"EMPLOYEE_ID": 5
},
{
"SID": 555,
"EMPLOYEE_NAME": "Test1555",
"EMPLOYEE_ID": 6
},
]
let sidNumbers = "789,543,123";
function newArr(arr, obj){
let newwArr = [];
let splitArr = arr.split(',');
splitArr.reduce((curr, acc)=>{
if(`${acc['SID']}`.includes(curr))
{
newwArr.push(acc)
}
},obj)
return newwArr;
}
console.log(newArr(sidNumbers, obj));
the first output firstArray = [{
"SID": 789,
"EMPLOYEE_NAME": "Test1789",
"EMPLOYEE_ID": 4
},
{
"SID": 543,
"EMPLOYEE_NAME": "Test1543",
"EMPLOYEE_ID": 2
},
{
"SID": 123,
"EMPLOYEE_NAME": "Test123",
"EMPLOYEE_ID": 1
}
]
the output of secondArray =[
{
"SID": 454,
"EMPLOYEE_NAME": "Test1454",
"EMPLOYEE_ID": 3
},
{
"SID": 999,
"EMPLOYEE_NAME": "Test1999",
"EMPLOYEE_ID": 5
},
{
"SID": 555,
"EMPLOYEE_NAME": "Test1555",
"EMPLOYEE_ID": 6
},
]
I have an array of object and string of numbers. Trying to create two new array of objects. first in which sidNumbers matches from the obj it filters an return the an array of object and in second the sidNumbers doesn’t matches from the obj it filters an return the an array of object. Is using reduce is the best way to solve this problem or is there any other way to solve this problem?
2
Answers
I would suggest you to use
filter
instead ofreduce
too get a clearer code.The only advantage of reduce is that it would iterate over the list only once, which only is relevant if you have a huge list (like, hundreds of thousands of elements)
In any case, here is how you could do I with
reduce
:Notes on the code above:
[firstArray, secondArray] = ...
– this is destructuring assignment. It means that I expect that the result of the expression will be an array with 2 elements, so I am assigning the first element into the variablefirstArray
and the second tosecondArray
.obj.reduce(([y,n], o) => ..., [[],[]])
– the functionreduce
takes 2 arguments. The first is a function and the second is the initial value (in this case, I am using an array of 2 empty arrays as initial value). The function must take 2 input parameters:y
andn
o
of the iteration overobj
sidNumbers.contains(o.SID)
– checking if the attributeSID
of the current object is included in yoursidNumbers
list.... ? [[...y, o],n] : [y,[...n, o]], [[],[]]
– this is the ternary conditional operator. If the condition returnstrue
, the function will return the value before the colon:
, which is just appending the current objecto
into the arrayy
. If it is false, appendo
into the second arrayn
.Use filter() and includes() instead of reduce(). Reduce is better suited for modifying elements to a new array.