There is a file that represents the accounting program database. My task is to calculate the sum of all orders. But here is the problem, the database has duplicate lines, because of this, the amount goes an order of magnitude higher.

Task: check order time and order number, if it is the same - ignore.

But I just can't figure out how to do it ...

Here, in fact, what is at the moment:

var xhr = new XMLHttpRequest(); var arr = []; var newArr = []; var dNewArr = []; var sum = 0; var dSum = 0; xhr.open('GET', 'input.mfl', false); xhr.send(); if (xhr.status !== 200) { alert(xhr.status + ': ' + xhr.statusText); } var file = xhr.responseText; var file = file.split('\n'); for (i = 0; i < file.length; i++) { arr = file[i].split('#') newArr.push(arr[4]) sum += parseFloat(newArr[i]); dNewArr.push(arr[6]) dSum += parseFloat(dNewArr[i]); } document.write('Без скидки: ' + sum + '<br>'); document.write('Со скидкой: ' + dSum + '<br>'); document.write('Скидка: ' + (sum - dSum)); 

Example input.mfl:

 742#?#Слава-Кассир#Слава-Кассир#15#0#15#2016@11@30@19@6@28#2016@11@30@19@6@28#False$Чернігівське світле розл. мал.#1 337#?#Слава-Кассир#Администратор#11132#20#8905.6#2016@11@30@16@1@58#2016@11@30@16@1@58#False$Салат из печени трески с гренками#4$Оливье с креветками и перепелиными яйцами#6$Сельдь под шубой#3$Мясная тарелка.#3$Рыбная тарелка.#3$Рыба фаршированная.#30$Холодец по-царски.#20$Блины с сёмгой и кремом из сыра "Буко"#5$Торт печёночный#3$Тарелка домашних солений.#3$Закуска из огурцов с укропом и чесноком.#3$Рулетики из баклажанов с мясом в томатном соусе.#3$Шампиньоны фаршированные моцареллой.#3$Свиные тефтели с черносливом.#3$Утка. запечённая с яблоками в медово-апельсиновой глазури.#42$Голубцы по-домашнему.#5$Хлеб#30$Каберне совіньйон червоне сухе#30$Одесса н/сол.#1$Козацька рада(Банкет)#20$Узвар#15$Картофель. запечённый ломтиками.#6 999#?#Слава-Кассир#Корбут О.#150#0#150#2016@11@30@18@9@55#2016@11@30@18@9@55#False$Американо#1$Молоко до кави#1$Чернігівське Біле розл. вел.#2$Чернігівське Біле розл. вел.#1$Чернігівське Біле розл. вел.#2 

Work can be viewed here: https://dream-studio.org.ua/project/

Closed due to the fact that off-topic participants Grundy , user194374, Dmitriy Simushev , user207618, Denis Bubnov 14 Feb '17 at 5:52 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Grundy, Community Spirit, Dmitriy Simushev, Community Spirit, Denis Bubnov
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    look here can help - vov4ok
  • one
    what exactly is there? what should be done? what exactly is not working? - Grundy
  • @ProstoJohn, all the necessary code, should be directly in the question - Grundy
  • @ vov4ok Already watched. I just have everything in one line, I divide it all into arrays var file = file.split('\n'); and loop through all these arrays, select and summarize the values. I can not understand how to exclude the same arrays. I understand that this should be before the cycle ... - ProstoJohn
  • 3
    Add an example of the contents of the input.mfl file so that it is clear what you load and how you parse - Grundy

2 answers 2

Something like this (the 2nd line is the same by date and ID, the filter will cut it):

 let source = `742#?#Слава-Кассир#Слава-Кассир#15#0#15#2016@11@30@19@6@28#2016@11@30@19@6@28#False$Чернігівське світле розл. мал.#1 742#?#Слава-Кассир#Слава-Кассир#15#0#15#2016@11@30@19@6@28#2016@11@30@19@6@28#False$Чернігівське світле розл. мал.#1 337#?#Слава-Кассир#Администратор#11132#20#8905.6#2016@11@30@16@1@58#2016@11@30@16@1@58#False$Салат из печени трески с гренками#4$Оливье с креветками и перепелиными яйцами#6$Сельдь под шубой#3$Мясная тарелка.#3$Рыбная тарелка.#3$Рыба фаршированная.#30$Холодец по-царски.#20$Блины с сёмгой и кремом из сыра "Буко"#5$Торт печёночный#3$Тарелка домашних солений.#3$Закуска из огурцов с укропом и чесноком.#3$Рулетики из баклажанов с мясом в томатном соусе.#3$Шампиньоны фаршированные моцареллой.#3$Свиные тефтели с черносливом.#3$Утка. запечённая с яблоками в медово-апельсиновой глазури.#42$Голубцы по-домашнему.#5$Хлеб#30$Каберне совіньйон червоне сухе#30$Одесса н/сол.#1$Козацька рада(Банкет)#20$Узвар#15$Картофель. запечённый ломтиками.#6 999#?#Слава-Кассир#Корбут О.#150#0#150#2016@11@30@18@9@55#2016@11@30@18@9@55#False$Американо#1$Молоко до кави#1$Чернігівське Біле розл. вел.#2$Чернігівське Біле розл. вел.#1$Чернігівське Біле розл. вел.#2`; // Хранилища уникальных ID и времени открытия let idStore = new Set(), timeStore = new Set(); let filtered = source.split(`\n`).filter(str => { // Извлекаем данные из очередной строки let [id,,,,,,, time] = str.trim().split('#'); // Если хранилище уже содержит это значение - сразу возвращаем false, что отфильтрует это значение if(idStore.has(id) && timeStore.has(time)) return false; else // Иначе добавляем (чтобы дальше дублей не копить) и продолжаем idStore.add(id), timeStore.add(time); return true; }).join(`\n`); console.info(filtered); 

  • probably you misunderstood me, you need to cut out only those that are the same in time and ID immediately - ProstoJohn
  • So? ........... - user207618
  • It works fine , only it returns an integer value, but I need a fractional ... - ProstoJohn

Divide your cycle into three steps:

  1. Prepares objects, parses, covers
  2. Filters
  3. Generates a result

When the flow is working refactorit

https://jsfiddle.net/ahde0srq/

 var result = { firstTotal : 0, secondTotal: 0 }; file.split('\n') .map(function(row){ var cols = row.split('#'); return { "id": cols[0], "first": parseFloat(cols[4]), "second": parseFloat(cols[6]) } }) .filter(function(row){ return row.first > 100; }) .forEach(function(row){ result.firstTotal += row.first; result.secondTotal += row.second; }); 
  • And what in this example does it specifically filter and how? Just filter and map have not used, that's not very clear :( - ProstoJohn