google script sheet, merging rows duplicate in array [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
lets say i have a 3D array data with something like this (dynamically duplicates, sometimes 2-5 records) after processing from a sheet get range and wanted to ouput a certain value format to a new sheet
[abc, 123, 456]
[abc, 123, 567]
[abc, 123, 644]
[xyz, 345, 434]
[xyz, 334, 345]
[aaa, 124, 433]
[aaa, 124, 435]
my goal now is to merge the result into something like this before writing to the sheet
[abc, 123, 456:567:644]
[xyz, 345, 434]
[xyz, 334, 345]
[aaa, 124, 433:435]
that is the result i wanted to have and write it to 3 column sheet, delimiter for : is actually , but i put : cause don't want to make it confuse in array form. as long as the first and 2nd column values are the same, we should make it become one row but concatenating the 3rd column values of the duplicate records into one row instead.
is it better to make a duplicate array and compare them and push to a new array with concatenating the 3rd column values together?

I would do something like this.
let rows = [
['abc', 123, 456],
['abc', 123, 567],
['abc', 123, 644],
['xyz', 345, 434],
['xyz', 334, 345],
['aaa', 124, 433],
['aaa', 124, 435],
['abc', 123, 5672],
]
function mergeRow (rows) {
let newRows = []
let matched = []
for (var i = 0; i < rows.length; i++) {
if (!matched.includes(i)) {
let a = rows[i]
let nextIndex = i+1
let matches = []
for (var x = nextIndex; x < rows.length; x++) {
if (a[0] === rows[x][0] && a[1] === rows[x][1]) {
matches.push(x);
}
}
let newRow = a
let lastItem = a[2]
matches.forEach(index => {
lastItem += ':' + rows[index][2]
matched.push(index)
})
newRow[2] = lastItem
newRows.push(newRow)
}
}
console.log('newRows', newRows)
}
mergeRow(rows);

Related

javascript Extract multiple series array from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have string like
var t = 'red: 5, purple: 7, fuchsia: 10, green: 8';
I want to make array like
a = ['red', 'purple', 'fuchsia', 'green'];
b = [ 5, 7, 10, 8]
Please help me
Sample solution:
const t = 'red: 5, purple: 7, fuchsia: 10, green: 8';
const tarr = t.split(', ');
const a = [];
const b = [];
for (const item of tarr) {
const [k, v] = item.split(': ');
a.push(k);
b.push(~~v); // '~~' is a shortcut to convert string value to number
}
console.log(a, b);

comparing two arrays to create a new array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This seems like a very straightforward problem but for the life of me, I can not get it sorted.
I want to compare two arrays and if the value of array2 is in array1 push it to a new array otherwise push a 0.
these are my arrays:
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let arrayTwo = [3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16];
desired outcome is
[0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
current attempt with obvious indices issues
let newArray = [];
for (let i=0; i < arrayOne.length; i++){
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
else newArray.push(0);
};
current result
[0, 0, 0, 8, 9, 10, 0, 0, 13, 14, 15, 16, undefined, undefined, undefined, undefined, undefined, 0]
Issue with your approach is that you are searching for an index in arrayTwo
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
where i is the index not a value. That's why you are getting undefined values, because arrayTwo has less values then arrayOne, so index of arrayOne will not exists in arrayTwo.
Instead you should search for value in arrayTwo
for (let i=0; i < arrayOne.length; i++){
let value = arrayOne[i];
if(arrayTwo.includes(value)) newArray.push(value);
else newArray.push(0);
};
If you check only for existence of the value in collection - use Set which designed exactly for this purpose.
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let values = new Set([3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16]);
const result = arrayOne.map(value => values.has(value) ? value : 0);
// => [0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]

Array of Objects check for equality and place accordingly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a very interesting Problem and would like to hear some approaches that you would take.
Scenario:
A Tournament of 32 Players, each represented in an Array of Objects ex:
[
{ player: 'Badgy', points: 5, place: tba, reward: 0 },
{ player: 'Ceff', points: 5, place: tba, reward: 0},
{ player: 'Niclas', points: 10, place: tba, reward: 0}
]
Now there are prices defined for each of the top places like:
1 Place = 100 Coins
2 Place = 50 Coins
3 Place = 10 Coins
Now in this example 'Ceff' and 'Badgy' have the same point amount, which means they both have to be place 2 and get the reward of (place2 + place3) / 2, each of them would get 30 coins in this example.
Now I tried around but I have a hard time finding a good solution to this case, specially if a 3+ way tie happens.
You could take a sum and an index for the first found group of same points and take the average for the last same group.
var prices = [100, 50, 20, 15, 10, 5, 2, 1],
points = [ 20, 10, 10, 5, 5, 5, 4, 3],
sum = 0,
index,
profit = points.reduce((r, v, i, { [i - 1]: last }) => {
if (last !== v) {
sum = 0;
index = i;
}
sum += prices[i];
var avg = sum / (i - index + 1);
while (i >= index) r[i--] = avg;
return r;
}, []);
console.log(profit);

how to pick from an array depending on a certain number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Lets say you use indexOf on an array to find all cases that say apple. If it comes back with three cases at positons 1, 2 and 3.
Now lets say there is an array = [10, 20, 30 ,40 ,50 ,60 ,70 ,80 ,90 ,100]
is there a way to use them cases 1,2 and 3 which come to 6. So is there a a way to go to position 6 "70" and produce that number. Depending on what the indexOf provides, is there a way to select that number from the array. Also if the indexOF produced 3.5 would there be a way to get 35 aka position 3.5.
If I understood correctly, you can use Array.reduce() to get the sum of the indexes where a match to some search term occurs. Then you can use the result from the reduce() to access your array of numbers:
let test = ["orange", "apple", "banana", "apple"];
let numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90];
const getSumOfIdxs = (arr, str) =>
{
return arr.reduce((acc, curr, idx) =>
{
if (curr === str)
{
if (acc < 0) acc += 1;
acc += idx;
}
return acc;
}, -1);
}
let res = getSumOfIdxs(test, "apple");
console.log("Sum of indexes: ", res);
console.log("Element from numbers: ", numbers[res]);
res = getSumOfIdxs(test, "hello");
console.log("Sum of indexes: ", res);
console.log("Element from numbers: ", numbers[res]);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Yes, you can - filter through the array and find all your apples, then map out the indexes from the original array, reduce to one index, and get the item at that index.
const arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
const appleNums = [20, 30, 40];
const resultingAppleNum = arr[arr.filter(e => appleNums.includes(e)).map(e => arr.indexOf(e)).reduce((acc, curr) => acc + curr)];
console.log(resultingAppleNum);

How to find the smallest numbers in a json file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is the best way to loop through a json object that contains integer values and select the smallest values?
For example, if I had an object that looks like this
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
And I wanted to pick out the 3 smallest numbers - 1,2,3 in this case- what's the best approach?
You could try the following script:
// create an array to store the values.
var numbers = [];
// loop through the keys of z and push each value in the numbers array.
for(var key in z){
numbers.push(z[key]);
}
// sort the array.
numbers = numbers.sort(function(a,b){ return a-b; });
// pick up the first three.
firstThree = numbers.slice(0,3);
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
var numbers = [];
for(var key in z){
numbers.push(z[key]);
}
numbers = numbers.sort(function(a,b){ return a-b; });
firstThree = numbers.slice(0,3);
alert(firstThree)
Get object values into an array using for...in loop. Then sort it using sort() and get the values
Update : You can get the first 3 values using splice()
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
arr = [];
// array for storing values
for (var o in z)
// iterate over the array
arr.push(z[o]);
// push value to the array
document.write(arr
.sort()
// sorting the value array
.splice(0, 3)
// get first three values
.join()
// joining the 3 values
)
I suggest to iterate over the keys of the object and use the keys for reducing the values to the smallest value.
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
smallest = Object.keys(z).reduce(function (r, k) {
return Math.min(r, z[k]);
}, Number.MAX_VALUE);
document.write(smallest);

Categories