How to efficiently add/push elements to an array if not already present

php add( //to array if not exists)
array push php
php check if value exists in associative array
php array push with key
in_array
php if string is not in array
php add to array in loop
php array element exists

I have one array with the name produtosSelecionados.

I need to create one function that every call push the elements produtosSelecionados to array produtosConfirmadosAnuncio, but the element don't have to push if this element is already in produtoConfirmadosAnuncio.

I try something like:

adicionaProdutoConfirmadosAnuncio(){
    for(let i=0;i<this.produtosSelecionados.length;i++){
      for(let j=i+1;j<this.produtosSelecionados.length;j++){
        if(this.produtosSelecionados[i] !== this.produtosSelecionados[j]){
          this.produtosConfirmadosAnuncio.push(this.produtosSelecionados[i]);
        }
      }
    }
    console.log(this.produtosConfirmadosAnuncio);
  }

But this way the elements is pushing repetead in my array produtosConfirmadosAnuncio. How can I do this?

I think you just need this code inside your method in place of nested loop.

Includes method helps to check if element already exist in an array.

if(!yourArray.includes(element){
    yourArray.push(element);
}

In your code specifically you need this :

adicionaProdutoConfirmadosAnuncio(){
    for(let i=0;i<this.produtosSelecionados.length;i++){
        if(!this.produtosConfirmadosAnuncio.includes(this.produtosSelecionados[i])){
            this.produtosConfirmadosAnuncio.push(this.produtosSelecionados[i]);
        }
    }
}

Using for..of

adicionaProdutoConfirmadosAnuncio(){
    for(let product of this.produtosSelecionados){
        if(!this.produtosConfirmadosAnuncio.includes(product)){
            this.produtosConfirmadosAnuncio.push(product);
        }
    }
}

php array_push() -> How not to push if the array already contains , If adding elements to an array that is not empty: Great answers are already present above, but if you have multiple array_push() all over your  push multiple elements at once. push to an array and slice. push to an array and sort. avoid gotchas. In the most general case, you can push an element to the end of the array (i.e., append) by performing an update with the $push operator. In the example below we use it to append an 'i' to the alphabet array.

You don't need to use double loop, this affect the effiency of the code. You can do:

adicionaProdutoConfirmadosAnuncio(){
    for(let producto of this.productosSeleccionados) {
          //indexOf return -1 if the item don't exist in the array
          if(this.productosConfirmadosAnuncio.indexOf(producto) === -1){
            this.productosConfirmadosAnuncio = [
                ...this.productosConfirmadosAnuncio,
                producto
            ]
      }
    }
}

Update: For good practices and more effiency use this for add elements instead of push. The method push modify the object, and this is more expensive than assign the variable, like my example.

Adding Elements to an Array (ActionScript: The Definitive Guide), The push( ) method appends one or more elements to the end of an array. element of the array, so we don't need to worry about how many elements already exist. When splice( ) performs both of these tasks in a single invocation​, it effectively Unlike push( ), concat( ) does not modify the array on which it is invoked  The javaScript push() method is used to add new elements to the end of an array. Note: javaScript push() array method changes the length of the given array. Here you will learn the following: How to add the single item of the array? How to add the multiple items of the array? How to push array into array in javaScript? How to add the single

Try

class MyClass {

  constructor() {
    this.produtosSelecionados = [{n:"P1"},{n:"P2"},{n:"P3"}];
    this.produtosConfirmadosAnuncio = [];
    this.produtosConfirmadosAnuncio.push(this.produtosSelecionados[0]) // put p1
  }

  adicionaProdutoConfirmadosAnuncio() {   
    this.produtosSelecionados.forEach( 
      p=> this.produtosConfirmadosAnuncio.includes(p) ? 0 : this.produtosConfirmadosAnuncio.push(p) );
    console.log(this.produtosConfirmadosAnuncio);
  }

}

let p = new MyClass();
p.adicionaProdutoConfirmadosAnuncio();

How to Check if an Array Contains a Value in Java Efficiently?, The approach may not be precise, but the idea is clear and simple. public static void main(String[] args)  Hence in order to add an element in the array, one of the following methods can be done: By creating a new array: Create a new array of size n+1, where n is the size of the original array. Add the n elements of the original array in this array. Add the new element in the n+1 th position. Print the new array.

Determine whether to push or update object in array based on , Your pushToArray function is less efficient than it could be because it it If the element hasn't existed it will be added, if it exists, it will be updated. to iterate all items if (element.id === obj.id) { arr[index] = obj; }; // The ; is not obj); // will replace existing if id is already used // or add if the id is not used. }. Adding elements to an array. The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array. let sports = ['soccer', 'baseball'] let total = sports.push('football', 'swimming') console.log(sports) // ['soccer', 'baseball', 'football', 'swimming'] console.log(total) // 4.

Array methods, We already know methods that add and remove items from the beginning or the end: arr.push(items) – adds items to the end,; arr.pop() – extracts an item from the end, The arr.splice(start) method is a swiss army knife for arrays. from) – looks for item starting from index from , returns true if found. Count of elements A[i] such that A[i] + 1 is also present in the Array; Choose two elements from the given array such that their sum is not present in any of the arrays; Sum of elements whose square root is present in the array; Program to find if two numbers and their AM and HM are present in an array using STL; Find if a crest is present in

List Manipulations, Python Tutorial: Changing and manipulating lists: removing elements with 'pop' You will learn how to append and insert objects to lists and you will also learn •​push This method is used to put a new object on the stack. The Python list class doesn't possess such a method, because it is not needed. Now with a tuple:. If you use array_push()to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

Comments
  • What type do elements of your arrays have? There are different rules used to compare primitives and objects developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Let me know if below is exactly what you are looking for
  • You should use includes method specifically if the element already exist in your array
  • Use a Set as a data structure, maybe order won't be maintained, but no duplicates will arise.