There is an array where rows of elements have the same text at the beginning, for example:

var myArray = [ "28|Какой то текст 1", "28|Какой то текст 2", "28|Какой то текст 3", "42|Какой то текст 4", "42|Какой то текст 5", "Фото1|Какой то текст 6", "Фото1|Какой то текст 7" ]; 

It is necessary to unite into groups (probably through two-level arrays?) All elements that start at 28 , all that start at 42, and all that start at Photo1 in this way to display them on the page in the following form:

 28: Какой то текст 1 Какой то текст 2 Какой то текст 3 42: Какой то текст 4 Какой то текст 5 Фото1: Какой то текст 6 Какой то текст 7 

The text at the beginning can be both a number and the actual text. The result is ultimately necessary without all the commas, brackets and round brackets to display in the textarea, where it will be copied to the clipboard, and then pasted into a plain text document

  • four
    tried anything yourself? :) - Grundy
  • one
    apparently, you need not a two-level array, but an object - Grundy
  • one
    Please try to solve the problem yourself, and in case of difficulties, ask a question about them already. The community does not write code for applications. - Risto
  • one
    Do not vandalize your own questions. Want to delete - delete (there is a button below the question) - Kromster
  • one
    @KromStern life is a pain. - PashaPash

2 answers 2

You can use the reduce function

 var myArray = [ "28|Какой то текст 1", "28|Какой то текст 2", "28|Какой то текст 3", "42|Какой то текст 4", "42|Какой то текст 5", "Фото1|Какой то текст 6", "Фото1|Какой то текст 7" ]; document.getElementById('s').innerHTML = JSON.stringify(myArray, null, 2); var result = myArray.reduce(function(acc, cur) { var parts = cur.split('|'); if (!acc[parts[0]]) acc[parts[0]] = []; acc[parts[0]].push(parts[1]); return acc; }, {}); document.getElementById('r').innerHTML = Object.keys(result).map(function(key){ return key+':\n' + result[key].join('\n'); }).join('\n\n'); 
 textarea { width: 200px; height: 250px; } 
 myArrr: <pre id="s"></pre> <textarea id="r"></textarea> 

    If a separator is used, then something like this:

     var obj = {}, arr = [ "28|text 1", "28|text 2", "28|text 3", "42|text 4", "42|text 5", "Foto1|text 6", "Foto1|text 7" ]; // Обрабатываем каждый элемент массива arr.forEach(function(item, i){ // Делим строку по разделителю var keys = item.split("|"); // Сохраняем ключ var key = keys[0]; // Удаляем первый элемент массива keys.shift(); // Если в объекте еще не существует массива с таким ключом, то создаем if(!obj[key]) { obj[key] = []; } // добавляем в объект остаток массива как строку obj[key].push(keys.join("")); }); document.getElementById("output").innerHTML = JSON.stringify(obj, null, 2); 
     <textarea id="output"></textarea>