5

I have a code like:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [1, 3] // ball and dog
var to = 5 // fish

for(var i in index){
  console.log(index[i])
  var local_data = data
  data.splice(to, 0, data.splice(index[i]), 1)
}

console.log(data)
console.log(index)

JsFiddle

Here var index = [1,3] is the index value of the data to be set.

What I want here is, to set the value of index i. e ball and dog after fish and the rest remains on the order.

After inserted I want the index value to be changed according to the new position of the ball and dog i. e [4, 5]

Updata

In the end I want the result like: console.log(data) should give

["apple", "cat", "elephant", "fish", "ball", "dog", "gorilla"]

and console.log(index) should give:

[4, 5] // new value of ball and dog
2
  • Can you rephrase your desired end result? Perhaps with the state of the variables you want at the end of the code? Commented Jun 21, 2016 at 5:46
  • @user01 check the update Commented Jun 21, 2016 at 5:56

4 Answers 4

1

you can do it in this way.

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [4, 5]; 
var to = 2  ;

var arrTemp = [];

data.forEach(function(val,key){

  if(index.indexOf(key)!=-1){

    data.splice((to+1),0,data[key]);
    to++;
    delete data[key];

  }
})
data = data.filter(function(val){ return val != undefined }); 

console.log(data)


UPDATE : 

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [ 2,3];
var to = 5 ;
var arrTemp = [];

data.forEach(function(val,key){

  if(index.indexOf(key)!=-1){    
    arrTemp.push(data[key]);
    delete data[key];

  }
})

to=to+1;
for(var pos=0;pos<index.length;pos++){
   data.splice(to++,0,arrTemp[pos])
}
data = data.filter(function(val){ return val != undefined }); 
 

JsFiddle

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

8 Comments

Few issues.. if I put index = [2, 3] its giving me null in 2 index.. and the value of index is not updated after splice
It gives correct value if I put something like [2, 4] but error on [2, 3]
thank you so much.. and how to update the index with new value ??
If you removed n item them subtract n from each index arr element
some errors over here like if index = [4,5] and to = 2 its giving weired error.. It is repeating 4th value..
|
1

Tricky problem but was fun solving it.

This is my solution, probably not the most efficient one but hey it got the work done.

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"];
var output = [];
var index = [1, 3]; // ball and dog
var to = 5; // fish

var extractValues = [];
index.forEach(function(i){
  extractValues.push(data[i]);
});

var valueToPutAfter = data[to];

// Put the value first
data.forEach(function(element) {
  if (element === valueToPutAfter) { // found element to push after
    output.push(element);
    extractValues.forEach(function(value){
      output.push(value);
    });
  }
  else {
    output.push(element);
  }

});


// Mark the position that needs to be deleted as null
var prevDelIndex = 0;
index.forEach(function(i){
  output[i] = null;
});

// delete the elements
output.forEach(function(element, index) {
  if (element == null) {
      output.splice(index, 1);
  }
});

console.log(output);
console.log(output.indexOf("ball"));
console.log(output.indexOf("dog"));

I have decompose your problem into a few small ones and tackle them in a systematic manner.

My approach is first loop through the data array and push all the elements including the new ones. Then go through the list again and mark those elements found in position, variable index array" as null and remove them.

Algorithm walkthrough:

  1. I first workout what needs to be extracted from the array (data).
  2. Similarly for the element that needs to be put after.
  3. I loop through the initial array to find that element mentioned in point (2), then start putting whatever needs to come after behind it.
  4. Now you will have an array which consists of the original value plus the new items.
  5. Using the garbage collection concept, I go through the new array and mark the "to-be-deleted" element as null. This is so that I know which element to delete with splice later.
  6. Once again, I loop through the new array looking for the flagged element (null) and remove them.

Now you will left with what you wanted.

Output:

[ 'apple', 'cat', 'elephant', 'fish', 'ball', 'dog', 'gorilla' ]

indexOf 'ball' = 4

indexOf 'dog' = 5

Comments

1

Wow, nice problem, really enjoyed hacking my way through this. I took a function approach since that's not done yet:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [2, 3] // ball and dog
var to = 5 // fish

var moveItemsToPosition = function (data, indices, to) {
  var movingItems = [];
  var after = data[to + 1];

  for (var i = 0 ; i < indices.length; i++) {
    // takes out the items that will be moved form the original array
    movingItems.push(data[indices[i] - i]);
    data.splice(indices[i] - i, 1);
  }

  // finds the new position of the item to move next to
  var pos = data.indexOf(after);
  var data2 = data.slice(pos, data.length);
  // join the items that will be moved
  data = data.slice(0, pos).concat(movingItems);
  data = data.concat(data2);
  // update the indices
  for (var i = 0 ; i < indices.length; i++) {
    // get the new indices
    indices[i] = data.indexOf(movingItems[i]);
  }

  return [data, indices];
}

console.log(moveItemsToPosition(data, index, to));

It returns both the updated array and the new indices. You can remove this as necessary. Basically the algorithm first takes out the items needed to be moved and then finds the item next to which it needs to be moved and places it there (with the help of fancy JS).

Hope this helps!

Comments

1

This works now in situ and uses some offset indicators like left for the extracting value and right for inserting the value.

After finishing, the indices are calculated based on the left offset.

Example for from = [1, 3, 6], to = 5

           from              from               to               from      offset
    0        1        2        3        4        5        6        7     left right
-------- -------- -------- -------- -------- -------- -------- -------- ----- ----- 
  apple   [ball]     cat     [dog]  elephant  (fish)   gorilla [banana]   0     0
  apple     cat     [dog]  elephant  (fish)   [ball]   gorilla [banana]  -1     0
  apple     cat   elephant  (fish)   [ball]    [dog]   gorilla [banana]  -2     0
  apple     cat   elephant  (fish)   [ball]    [dog]  [banana]  gorilla  -2     1

function juggle(data, from, to) {
    var left = 0,
        right = 0;

    from.forEach(function (a) {
        if (a + left < to) {
            data.splice(to, 0, data.splice(a + left, 1)[0]);
            left--;
        } else {
            right++;
            data.splice(to + right, 0, data.splice(a, 1)[0]);
        }
    });
    from.forEach(function (_, i, a) { a[i] = to + left + i + 1; });
}

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla", "banana"],
    index = [1, 3, 7], // ball dog banana
    to = 5;            // fish
   
juggle(data, index, to);
console.log(data);
console.log(index);

data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla", "banana"];
index = [4, 5];        // elephant fish
to = 2;                // cat

juggle(data, index, to);
console.log(data);
console.log(index);

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.