0

I am pushing element in the array using javascript .

and i am getting output like this

["api", "management", "provision", "tenant", "external", "provider"]  => Correct

after pushing the data into array now i want append two element from the array management and provision and want output like this

["api", "management/provision", "tenant", "external", "provider"]

how would i do this ?

any example would be good for me

thanx in advance

1
  • 3
    Remove them both, concatenate the strings and then add the concatenated string back to the array. What have you tried so far? Commented Apr 1, 2016 at 12:29

4 Answers 4

4

The simplest thing you can do is to remove them both, join with / and put at the right place. You can do this in a few lines of code:

const input = ["api", "management", "provision", "tenant", "external", "provider"];
input.splice(1, 3, input.slice(1, 3).join('/'));
// now input contains ["api", "management/provision", "external", "provider"]

This can be further made more readable and reusable:

function mergeTerms(startIndex, endIndex, array) {
    const input = array.slice(0); // make a shallow copy of the array in order not to mutate it
    input.splice(startIndex, endIndex, input.slice(startIndex, endIndex).join('/'));
    return input;
}

and then:

mergeTerms(1, 3, input);
Sign up to request clarification or add additional context in comments.

Comments

1

Lets say its the var array that holds the values.

var temp = array.splice(2,3);
array[1] = array[1]+"/"+temp;

Comments

1
function mergeArrayEntries(e1, e2, arr) {
var index = -1;
   for (var i = 0; i < arr.length; i++) {
     if (arr[i] == e1) {
       index = i;
     }
     if (arr[i] == e2 && index > -1) {
       arr[index] = arr[index]+"/"+arr[i];
       arr.splice(i, 1);
     }
   }
}

this function searches for e1 and e2 in the arr and once found, it merges them to position of e1 and deletes e2 entry in arr.

hope it helps

Comments

1

Not the nicest code, and not at all reusable, but will give you what you are looking for --- just another approach

var array = ["api", "management", "provision", "tenant", "external", "provider"];
var subArray = [];
subArray.push(array[1]);
subArray.push(array[2])
array.splice(1, 2);
subArray = subArray.join("/")
array.splice(1, 0, subArray);

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.