need add object to array if name not exist (js)

Trying add object to array if name not exist . but have dublicates. For example array: [{day:"mo"},{day:"tu"},{day:"st"}].

need to add {day:we} if it not in array. so first need to check if {day:we} not in array then add it.

result: [{day:"mo"},{day:"tu"},{day:"we"},{day:"st"}].

for (name in result) {
            if(name !== 'mo') {
              result.push({day:'mo'});
            }
            if(name !== 'tu') {
              result.push({day:'tu'});
            }
            if(name !== 'we') {
              result.push({day:'we'});
            }
            if(name !== 'th') {
              result.push({day:'th'});
            }
            if(name !== 'fr') {
              result.push({day:'fr'});
            }
            if(name !== 'sa') {
              result.push({day:'sa'});
            }
            if(name !== 'su') {
              result.push({day:'su'});
            }
              break;
          }

Upvotes: 1

Views: 7309

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386736

You could check if the right order of the days is given and insert before a greater day number.

function add(array, insert) {
    var days = { mo: 0, tu: 1, we: 2, th: 3, fr: 4, sa: 5, su: 6 };

    array.some(function (a, i, aa) {
        if (days[a.day] === days[insert.day]) {
            return true;
        }
        if (days[insert.day] < days[a.day]) {
            aa.splice(i, 0, insert);
            return true;
        }
    }) || array.push(insert);
}

var array = [{ day: "tu" }, { day: "sa" }];

add(array, { day: "tu" }); // no insert
console.log(array);

add(array, { day: "mo" }); // insert at the beginning
console.log(array);

add(array, { day: "we" }); // insert in the middle
console.log(array);

add(array, { day: "su" }); // insert at the end
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26390

let days = [{day:"mo"},{day:"tu"},{day:"st"}]
let toAdd = ["mo","tu","wed","thu","fri"]

toAdd.forEach( day1 => {
	if(!days.find( day2 => day2===day1 )) days.push({day:day1})
})

console.log(days)

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138457

You may filter an array of days and check if they exist in result already:

["mo","tu","we","th","fr","sa","su"]
  .filter( day => ! result.some(obj => obj.day === day))
  .forEach( day => {
    result.push({day});
  });

More performant version:

var days = new Set( ["mo","tu","we","th","fr","sa","su"]);

result.forEach( day => days.delete(day.day));

days.forEach(day => result.push({day}));

Upvotes: 3

Related Questions