How to validate array of objects in an async function? - javascript

I am sending array of objects to server and trying to validate it, but I fail it will not do anything, if array is empty or neither it is valid, it just does not work, and I want to know why?
Here is code I use:
const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
ingredient.trim().length == 0 || quantity.trim().length == 0
})
if(ingredientValidator){
return res.status(409).send({
message: 'fully point ingredients'
})
}
what is problem with this?
P.S example of array of objects:
[
{
ingredient:'foo',
quantity:'bar'
},
{
ingredient:'foo',
quantity:'bar'
},
{
ingredient:'foo',
quantity:'bar'
}
]
How do I solve the problem?

I think you just need to alter the return of ingredientValidator:
const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
return ingredient.trim().length == 0 || quantity.trim().length == 0
});
// or
const ingredientValidator = ingredients.some(({ingredient, quantity})=>
ingredient.trim().length == 0 || quantity.trim().length == 0
);
When you have curly brackets after the arrow, it's essentially a normal function block that needs a return in order to pass anything out. You can also just remove the curly blocks and it should act as expected to get the implicit return.

Related

If-statement not filtering out undefined

I am trying to cleanse a dataset, but my if statement appears not to work.
The first part, x.sites.length>0, seems to work by itself.
The second part, (x !== undefined), doesn't seem to register at all. In my return Array, some of the undefineds are still there. I have tried various different ways of writing (x !== undefined), but none of them seem to work for me.
Any thoughts?
export function clenseData(dataset){
let cleansedSet = dataset.map(x=>{
if(x.sites.length>0 && (x !== undefined))
{return x;}//doesn't work.
})
console.log(cleansedSet);
debugger;
return cleansedSet;
}
Here is the JSON String for one of the inputs: {"data":{"success":true,"data":[{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Roxanne Modafferi","Valentina Shevchenko"],"commence_time":1555754400,"home_team":"Roxanne Modafferi","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[3.35,1.3]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[3.8,1.27]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[3.35,1.3]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[3.75,1.28]}},{"site_key":"williamhill","site_nice":"William Hill","last_update":1555332878,"odds":{"h2h":[3.25,1.33]}}],"sites_count":5},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Marcin Tybura","Shamil Abdurakhimov"],"commence_time":1555754400,"home_team":"Marcin Tybura","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.57,2.3]}},{"site_key":"matchbook","site_nice":"Matchbook","last_update":1555333223,"odds":{"h2h":[1.63,2.39]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.55,2.4]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.57,2.3]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[1.6,2.31]}},{"site_key":"williamhill","site_nice":"William Hill","last_update":1555332878,"odds":{"h2h":[1.53,2.38]}}],"sites_count":6},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Aleksei Oleinik","Alistair Overeem"],"commence_time":1555754400,"home_team":"Alistair Overeem","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.9,1.4]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.9,1.4]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[2.96,1.41]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.9,1.41]}},{"site_key":"williamhill","site_nice":"William Hill","last_update":1555332878,"odds":{"h2h":[2.9,1.4]}}],"sites_count":5},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Keita Nakamura","Sultan Aliev"],"commence_time":1555754400,"home_team":"Sultan Aliev","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.8,1.95]}},{"site_key":"matchbook","site_nice":"Matchbook","last_update":1555333223,"odds":{"h2h":[1.85,1.97]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.81,2]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.8,1.95]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[1.86,1.92]}},{"site_key":"williamhill","site_nice":"William Hill","last_update":1555332878,"odds":{"h2h":[1.8,1.91]}}],"sites_count":6},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Alexander Volkov","Luis Henrique Da Silva"],"commence_time":1555786800,"home_team":"Luis Henrique Da Silva","sites":[{"site_key":"ladbrokes","site_nice":"Ladbrokes","last_update":1555333247,"odds":{"h2h":[1.74,2.05]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.66,2.23]}},{"site_key":"betfair","site_nice":"Betfair","last_update":1555332863,"odds":{"h2h":[1.66,2.18]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Marcin Tybura","Shamil Abdurakhimov"],"commence_time":1555790400,"home_team":"Shamil Abdurakhimov","sites":[{"site_key":"ladbrokes","site_nice":"Ladbrokes","last_update":1555333247,"odds":{"h2h":[1.55,2.4]}},{"site_key":"betfair","site_nice":"Betfair","last_update":1555332863,"odds":{"h2h":[1.53,2.48]}}],"sites_count":2},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Keita Nakamura","Sultan Aliev"],"commence_time":1555790400,"home_team":"Sultan Aliev","sites":[{"site_key":"ladbrokes","site_nice":"Ladbrokes","last_update":1555333247,"odds":{"h2h":[1.8,2]}},{"site_key":"betfair","site_nice":"Betfair","last_update":1555332863,"odds":{"h2h":[1.79,1.99]}}],"sites_count":2},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Roxanne Modafferi","Valentina Shevchenko"],"commence_time":1555790400,"home_team":"Roxanne Modafferi","sites":[{"site_key":"matchbook","site_nice":"Matchbook","last_update":1555333223,"odds":{"h2h":[3.78,1.3]}},{"site_key":"ladbrokes","site_nice":"Ladbrokes","last_update":1555333247,"odds":{"h2h":[3.7,1.27]}},{"site_key":"betfair","site_nice":"Betfair","last_update":1555332863,"odds":{"h2h":[3.45,1.28]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Aleksei Oleinik","Alistair Overeem"],"commence_time":1555801200,"home_team":"Aleksei Oleinik","sites":[{"site_key":"betfair","site_nice":"Betfair","last_update":1555332863,"odds":{"h2h":[3.05,1.45]}},{"site_key":"matchbook","site_nice":"Matchbook","last_update":1555333223,"odds":{"h2h":[2.95,1.42]}},{"site_key":"ladbrokes","site_nice":"Ladbrokes","last_update":1555333247,"odds":{"h2h":[3,1.39]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Alex Oliveira","Mike Perry"],"commence_time":1556406000,"home_team":"Mike Perry","sites":[],"sites_count":0},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Cory Sandhagen","John Lineker"],"commence_time":1556406000,"home_team":"Cory Sandhagen","sites":[{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.15,1.65]}},{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.15,1.65]}}],"sites_count":2},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jack Hermansson","Ronaldo Souza"],"commence_time":1556413200,"home_team":"Jack Hermansson","sites":[{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.15,1.7]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.25,1.62]}},{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.25,1.62]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Glover Teixeira","Ion Cutelaba"],"commence_time":1556413200,"home_team":"Glover Teixeira","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.2,1.62]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.24,1.65]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[2.31,1.63]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.2,1.62]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Court McGee","Dhiego Lima"],"commence_time":1556413200,"home_team":"Court McGee","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.62,2.2]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.6,2.33]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.62,2.2]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Andrei Arlovski","Leonardo Augusto Guimaraes"],"commence_time":1556413200,"home_team":"Andrei Arlovski","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.1,1.68]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.22,1.66]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.1,1.68]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jessica Penne","Jodie Esquibel"],"commence_time":1556413200,"home_team":"Jessica Penne","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.55,2.35]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.51,2.55]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.55,2.35]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jason Gonzalez","Jim Miller"],"commence_time":1556413200,"home_team":"Jim Miller","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.25,1.6]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.27,1.63]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.25,1.6]}}],"sites_count":3},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Alex Volkanovski","Jose Aldo"],"commence_time":1557622800,"home_team":"Jose Aldo","sites":[{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.05,1.72]}},{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.05,1.72]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.09,1.74]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[2.12,1.74]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jessica Andrade","Rose Namajunas"],"commence_time":1557626400,"home_team":"Rose Namajunas","sites":[{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.65,2.2]}},{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.65,2.2]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.71,2.13]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[1.7,2.18]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Alexander Gustafsson","Ashlee Evans Smith"],"commence_time":1559422800,"home_team":"Alexander Gustafsson","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.44,2.7]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.48,2.6]}}],"sites_count":2},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jessica Eye","Valentina Shevchenko"],"commence_time":1560045600,"home_team":"Valentina Shevchenko","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[6,1.12]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[6,1.12]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[6.25,1.12]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[8,1.08]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Henry Cejudo","Marlon Moraes"],"commence_time":1560049200,"home_team":"Henry Cejudo","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[2.1,1.72]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[2.1,1.72]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[2.12,1.74]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[2.09,1.74]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Amanda Nunes","Holly Holm"],"commence_time":1562464800,"home_team":"Amanda Nunes","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.3,3.45]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.3,3.45]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.3,3.5]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[1.31,3.52]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Jon Jones","Thiago Santos"],"commence_time":1562468400,"home_team":"Jon Jones","sites":[{"site_key":"unibet","site_nice":"Unibet","last_update":1555332974,"odds":{"h2h":[1.14,5.5]}},{"site_key":"sport888","site_nice":"888sport","last_update":1555332928,"odds":{"h2h":[1.14,5.5]}},{"site_key":"nordicbet","site_nice":"Nordic Bet","last_update":1555332998,"odds":{"h2h":[1.17,5]}},{"site_key":"marathonbet","site_nice":"Marathon Bet","last_update":1555332887,"odds":{"h2h":[1.16,5.4]}}],"sites_count":4},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Colby Covington","Kamaru Usman"],"commence_time":1562475600,"home_team":"Colby Covington","sites":[],"sites_count":0},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Dustin Poirier","Khabib Nurmagomedov"],"commence_time":1568523600,"home_team":"Dustin Poirier","sites":[],"sites_count":0},{"sport_key":"mma_mixed_martial_arts","sport_nice":"MMA","teams":["Israel Adesanya","Robert Whittaker"],"commence_time":1569697200,"home_team":"Israel Adesanya","sites":[],"sites_count":0}]},"status":200,"statusText":"","headers":{"x-requests-remaining":"24","content-type":"application/json;charset=utf-8","x-requests-used":"126"},"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"headers":{"Accept":"application/json, text/plain, */*"},"method":"get","url":"https://api.the-odds-api.com/v3/odds/?apiKey=b80b98e306cbe877f35c7db3804d2d72&sport=mma_mixed_martial_arts&region=uk&mkt=h2h"},"request":{}}
Are you trying to filter the data? if so you should be using filter function & not map. The map is used when you want to iterate over the data.
export function clenseData(dataset){
let cleansedSet = dataset.filter(x => {
if(x !== undefined && x.sites.length > 0) {
return true; // if you want to include it in the cleaned data
}
})
return cleansedSet;
}
The every() method tests whether all elements in the array pass the test implemented by the provided function:
dataset.every((x) => x !== undefined && x.sites.length> 0);

Comparing problem with If else statement in Javascript

I have two condition of my same JSON data:
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[
{
"letterNo":13,
"letterId":1,
"inout":"out",
"inoutNo":"12332466544",
"inoutDate":"2070-01-01",
"letterIssuedSubBy":null,
"letterFile":null,
"representativeName":null,
"representativeNameEng":null,
"selectionId":124,
"assessmentNo":null,
"entryBy":"user98",
"rStatus":"I",
"others":null,
"signatary":"qwerrt",
"letterBox":null,
"imageFile":null,
"imageTitle":null,
"reminderYesNo":"N"
}
]
}
Same JSON with letter array empty structure :
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[]
}
All these values are stored in
var trDataSecondTable; . I tried to compare if the letter is empty or not by using if condition:
if(trDataSecondTable.letter != null) {
console.log("asasfasdfdsfdsfds");
$("#inoutDate").val(trDataSecondTable.letter[0].inoutDate);
$("#inoutNo").val(trDataSecondTable.letter[0].inoutNo);
$("#signatary").val(trDataSecondTable.letter[0].signatary);
}
else
{
console.log("entered in else part");
}
Though "letter":[] is empty it is not entering into else part. While comparing i also tried trDataSecondTable.letter.length != 0 but also it is not entering into else part.
Your condition should check for both null and the length:
if (trDataSecondTable.letter != null && trDataSecondTable.letter.length > 0)
Is is important to check for null before accessing the length property as it guarantees you won't try to access the length property on null, which would raise an exception. This is important since data is rarely reliable.
Because of the && operator, if the first check fails, the second check won't be evaluated.
Actually, an even safer way would be to check if the value is truthy, as this will work for null and undefined:
if (trDataSecondTable.letter && trDataSecondTable.letter.length > 0)
You could check the length of the array.
if (trDataSecondTable.letter.length) {
// letter has some elements
} else {
// no elements
}
I think this condition is enough
if(trDataSecondTable.letter.length)

Optimize a function that ensures an object's properties does not have any of these values

I have an array of objects that represent form fields. I want to make sure that none of the elements in the array have their initial values. As in all fields need to be updated. The initial value is below. I'd like a simple function that checks each element and ensures none of these properties have the default fields.
[
{
key: 0,
name: '',
typeLabel: '',
typeValue: 0,
value: '',
}
...
]
Looking for help on improving this
collection.every((obj) => {
if (obj.key === 0) return false;
if (obj.name === '') return false;
if (obj.typeLabel === '') return false;
if (obj.typeValue === 0) return false;
if (obj.value === '') return false;
return true;
});
EDIT: Actually just thought of this
collection.every((obj) => {
const values = Object.values(obj);
return values.includes(0, '');
});
To be honest I'm not sure how much more better you can make it, it looks pretty decent to me! Any changes I'd make would be subjective changes that don't actually matter. Curious what other people will answer with though, maybe I'm missing something :)
I mean you could do this and it's arguably less if/elses and uses a named function to explain what it is doing which is maybe nicer? But meh I don't think this matters all that much:
function inputValueHasBeenSet(inputObject) {
return !!inputObject.key &&
!!inputObject.name &&
!!inputObject.typeLabel &&
!!inputObject.typeValue &&
!!inputObject.value;
}
collection.every(inputValueHasBeenSet);

Using Filter Function to Find Values Equal to False and Setting to True

In my Angular app I have a function that drills down to an array, and then uses a filter function to pull out values in a new array where "completed" is "false".
This is working as expected. And the way our data is, there is always one object in the array that has the property for "completed" set to "false", so I can target [0] to get to that. So, from there all I need to do is set it to "true". However, for whatever reason, how to accomplish this last step is eluding me.
This is my whole function, and what I've tried thus far:
private completeLastWorkflowStatus() {
let currentService = this.checkDiscipline();
for (let service of this.client.services) {
if (service.service === currentService) {
let targetWorkflow = service.workflow;
let inCompleteWorkflow = targetWorkflow.filter(workflow => workflow.completed === false);
console.log(inCompleteWorkflow);
if (inCompleteWorkflow[0].completed === false) {
inCompleteWorkflow[0].completed === true;
console.log(inCompleteWorkflow[0].completed);
}
}
}
}
For the last console.log listed above, I still get "false" as the value. What am I missing here? How can I set the value of "completed" to "true" for this one object in the array?
inCompleteWorkflow[0].completed === true; is not assignment. Do inCompleteWorkflow[0].completed = true;

How to check if an Object already exists in an Array before adding it?

I have this algorithme issue, I would like to check if an Object is already present in my Array before adding it.
I tried many different approaches (indexOf, filter...), and my last attempt is with an angular.foreach.
The problem is my $scope.newJoin remains always empty. I understood why, it's because the if is never read, because of the 0 size of my $scope.newJoin, but I don't know how to figure this out...
$scope.newJoinTMP is composed by : 6 Objects, within each a timePosted attribute (used for compare these different array Objects).
$scope.newJoin is an empty Array. I want to fill it with the Objects inside $scope.newJoinTMP but with the certainty to have once each Objects, and not twice the same ($scope.newJoinTMP can have duplicates Objects inside, but $scope.newJoin mustn't).
angular.forEach($scope.newJoinTMP, function(item)
{
angular.forEach($scope.newJoin, function(item2)
{
if (item.timePosted === item2.timePosted)
{
//snap.val().splice(snap.val().pop(item));
console.log("pop");
}
else
{
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
}
});
});
if(!$scope.newJoin.find(el=>item.timePosted===el.timePosted){
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
}
You dont want to push inside an forEach, as it will push multiple times...
There might be better ways to handle your particular situation but here's a fix for your particular code.
Replaced your inner for each with some which returns boolean for the presence of element and by that boolean value, deciding whether to add element or not
angular.forEach($scope.newJoinTMP, function(item)
{
var isItemPresent = $scope.newJoin.some(function(item2)
{
return item.timePosted === item2.timePosted;
//you dont need this conditional handling for each iteration.
/* if (item.timePosted === item2.timePosted)
{
//snap.val().splice(snap.val().pop(item));
console.log("pop");
}
else
{
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
} */
});
if( ! isItemPresent ) {
$scope.newJoin.push(item);
} else {
//do if it was present.
}
});
If you want to avoid the nested loop (forEach, some, indexOf, or whatever) you can use an auxiliar object. It will use more memory but you will spent less time.
let arr = [{ id: 0 }, { id:0 }, { id: 1}];
let aux = {};
const result = arr.reduce((result, el) => {
if (aux[el.id] === undefined) {
aux[el.id] = null;
return [el, ...result];
} else {
return result;
}
}, []);
console.log(result);
You can use reduce
$scope.newJoin = $scope.newJoinTMP.reduce(function(c, o, i) {
var contains = c.some(function(obj) {
return obj.timePosted == o.timePosted;
});
if (!contains) {
c.push(o);
}
return c;
}, []);
The problem with your current code is, if newJoin is empty, nothing will ever get added to it - and if it isnt empty, if the first iteration doesn't match the current item being iterated from newJoinTMP - you're pushing.

Categories