0

I have two JavaScript arrays, one current and one new. I can append new elements of Strings from the new array into the current array, and ONLY new elements.

For example, if I have two arrays currentArray = [a,d] and newArray = [a,b,c,d,e], we can see that elements b,c, and e are different (and thus can be appended to currentArray).

My UI allows me to select only the new elements from the new array to append. But currently, it only appends to the current at the end of the array.

If I were to select element b, I want the current array to be currentArray = [a,b,d], not currentArray= [a,d,b].

If I were to select element b, and then c, the current array should be currentArray= [a,b,c,d]

How do I implement this logic?

4
  • Is a2 a base array or something which is constant? Commented Dec 15, 2015 at 20:16
  • What have you researched and tried regarding Array manipulation? Also you did not specified if those are strings, numbers or what Commented Dec 15, 2015 at 20:17
  • I edited the question to be more clear. a2 is the new array. Commented Dec 15, 2015 at 20:17
  • Where's the JavaScript that you tried? We also need a complete code example to see how you're doing what you're doing. Also, are the array elements just the single characters a..z? Commented Dec 15, 2015 at 20:17

1 Answer 1

1

You can use this logic:

var baseArray = ["a", "b", "c", "d", "e"];

function appendEl(arr, element){

  // Parse through baseArray for every possible element.
    return baseArray.filter(function(el){
    // If element is in arr or is the element itself.
    if(arr.indexOf(el)!=-1 || el==element) return true;
    else return false;

  });

}

Fiddle

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

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.