B
B
busidoway2021-02-11 16:02:51
JavaScript
busidoway, 2021-02-11 16:02:51

How to remove duplicates from a JavaScript array?

I'm uploading images to the server. On the client side, I collect data about uploaded files into an array and send this array to the server. How to remove duplicates from an array when the user has re-uploaded some image files? Or, in advance, collect only unique data in the array.

// загрузка изображения
var file_upload = $('#file_upload');
var arr_files = [];

file_upload.on('change', function(){
  
  if((file_upload[0].files).length !=0){
    $.each(file_upload[0].files, function(i, file){
      
      //добавление в массив
      arr_files.push(file);

    });
  }
    
  // Далее отправка через ajax 
  //......
  //......
      
});


The array of files looks something like this:
60252a376199f710335803.jpeg

I found this solution on the Internet:

let set = new Set(arr_files.map(JSON.stringify));
let arr_files_uniq = Array.from(set).map(JSON.parse);


But for some reason it removes all elements from the array, except for the first one.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
busidoway, 2021-02-11
@busidoway

Problem solved. Thanks for the comments Vadim

// загрузка изображения
var file_upload = $('#file_upload');
var files_obj= {};

file_upload.on('change', function(){
  
  if((file_upload[0].files).length !=0){
    $.each(file_upload[0].files, function(i, file){
      
      //добавляем данные в созданный объект
      files_obj[file.name] = file;

    });
  }
    
  let arr_files = Object.values(files_obj);

  // Далее отправка через ajax 
  //......
  //......
      
});

V
VitalyChaikin, 2021-02-11
@VitalyChaikin

See
https://stackoverflow.com/questions/15125920/how-t...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question