0

I have the next situation in JavaScript:

const arr1 = [1,2,3];  // by default it is empty `[]`
const arr2 = [2,1,8,9];

arr1 can be changed dynamicly. So sometimes it could be [1,2,3,4] or [4,2,3] and so on.

The idea is next:

Depending by the arr1 to change the arr2 like,
if in arr1 is a number which is equal with a number from arr2,
then the number from arr2 that is equal should be deleted,
but if the new number that is added in arr1 is not exists in arr2 then it should be added in arr2:
EX:

  1. arr1 = []; arr2=[2,1,8,9] // nothing happens
  2. arr1 = [1]; arr2=[2,8,9] // 1 from arr2 is deleted
  3. arr1 = [1,8,9,7]; arr2=[1,2,7] // 1,8,9 from arr2 is deleted, 7 is added
2
  • arr1 and / or arr2 can be very big array sized ( more than 1000 elements ? , 10000, 100000... ) ? Commented Feb 26, 2021 at 0:08
  • @MisterJojo, no Commented Feb 26, 2021 at 5:46

2 Answers 2

2

Let me explain the logic.. for each elem in arr1, if arr2 has the elem(arr2.indexOf(a)!=-1), run a while loop that will stop when ALL elems in arr2 that match the specific elem in arr1 are removed
Lastly the else logic would activate if arr2 DOES NOT contain specific elem

const arr1 = [1,2,3];  // by default it is empty `[]`
const arr2 = [2,1,8,9];

function updateArr(arr1,arr2){
  arr1.forEach(a=>{
    let index=arr2.indexOf(a)
    if(index!=-1){
      while(index!=-1){arr2.splice(index,1);index=arr2.indexOf(a)}
    }
    else{arr2.push(a)}
  })
  return arr2
}

//function that takes in 2 vars, uses the first to edit the second

console.log(updateArr([2,3,7,9], [2,1,8,9]))
console.log(updateArr(arr1,arr2))
console.log("No cap it works\n",arr2)

Sign up to request clarification or add additional context in comments.

4 Comments

could you show also an example using react js hooks like useState, like const [arr2, setArr2] = useState([1,2,3]). How to change the state in this situation?
ok im gonna come clean with u.. i havent really learned react(secondary school year gonna be over soon so that gonna change) but I CAN make a function
could you help with the function?
oh.. just made a slight syntax error.. my bad.. check it now
0

In a simple words, you want to keep only uniques elements of Arr1 and Arr2, and give the result in Arr2 (not in a new array)

function updArr2(arr1, arr2)
  {
  let set1 = new Set(arr1)
    , plus = arr1.filter(x=>!arr2.includes(x))

  for(let i=arr2.length;i--;)  
    if (set1.has(arr2[i])) arr2.splice(i,1)

  plus.forEach(e => arr2.push(e) )
  }

const
  arr_1 = [1,2,3] 
, arr_2 = [2,1,8,9]
;
updArr2(arr_1, arr_2)


console.log( JSON.stringify(arr_2) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.