0

I guess i do something stupid so forgive me, but both methods don't change anything .

I want to move element from certain index - into index 0 . I have an array with 2 elements .

first way

console.log(index); //1
console.log(localProductPhotos);
localProductPhotos.unshift(localProductPhotos.splice(index, 1)[0]);
console.log(localProductPhotos);

array will stay/print the same order

second way

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};
    localProductPhotos.move(index,0); //index prints 1

both cases the array prints the same order.

EDIT:

This is the print:

log

EDIT: The above works on a simple array of strings, but my array is array of blob files as you can see in the photo.

    var localProductPhotos=[];
//...
  localProductPhotos.push(file);
hkrly
  • 311
  • 3
  • 12
  • Why are you using splice? – ninesalt Jul 14 '19 at 10:06
  • please add an example. – Nina Scholz Jul 14 '19 at 10:08
  • 1
    Please create a [mcve]. Both of these look fine. – adiga Jul 14 '19 at 10:10
  • sorry i have edited to show my log. – hkrly Jul 14 '19 at 10:15
  • @ninesalt this is the examples i see online, is it not good ? – hkrly Jul 14 '19 at 10:16
  • 1
    That is just how the logging works. You log the same array with references to objects, so once you expand them you see their current state which is the swapped array. Try logging with `console.log(JSON.stringify(localProductPhotos));` in both cases and you will see your code works fine. – Gabriele Petrioli Jul 14 '19 at 10:19
  • [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440) and [Why does javascript object show different values in console in Chrome, Firefox, Safari?](https://stackoverflow.com/questions/8249136) – adiga Jul 14 '19 at 10:22
  • thanks sorry i didn't get it. file number 3 did not change position inside the array. can you explain more ? – hkrly Jul 14 '19 at 10:23
  • @GabrielePetrioli thanks i tried but this way it prints empty - [{},{}] – hkrly Jul 14 '19 at 10:24
  • @adiga it prints [{},{}] with stringify – hkrly Jul 14 '19 at 10:28
  • The important thing is that your code works. The problem is how the logging works (*the `JSON.stringify` cannot handle `File` objects*). Try `console.log(localProductPhotos[0].name, localProductPhotos[1].name)` – Gabriele Petrioli Jul 14 '19 at 11:18

1 Answers1

-2

Based on your example/log, I can surmise that you want to move the element in your index to the first one. So you can just do this:

localProductPhotos.unshift(localProductPhotos[index]);
ninesalt
  • 4,054
  • 5
  • 35
  • 75