How to flatten a two dimensional array in javascript [closed] - javascript

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 9 days ago.
The community is reviewing whether to reopen this question as of 8 days ago.
Improve this question
This is an example. Values can be text, numbers, or more values.
var array = [[1,2],[ [3,4],[5,6] ],[1,2],[1,2]]
This is the result I want (Note [3,4],[5,6]).
var flattened = [[1,2],[3,4],[5,6],[1,2],[1,2]]

Use Array.flatMap() to iterate the array a flatten the 1st level of sub-arrays. Wrap in another array all elements that are 1 dimension deep.
const a = [[1,2],[[3,4],[3,4]],[1,2],[1,2]]
const result = a.flatMap(v =>
Array.isArray(v[0]) ? v : [v]
)
console.log(result)
Using reduce iterate the array. Combine the current element (v) with the accumulator (acc) by spreading (2 dimensions), or by add (1 dimension).
const a = [[1,2],[[3,4],[3,4]],[1,2],[1,2]]
const result = a.reduce((acc, v) =>
Array.isArray(v[0])
? [...acc, ...v] // 2d
: [...acc, v] // 1d
, [])
console.log(result)

You can flatten the array with a simple reduce (if you have only one level of nesting)
const result = aa.reduce((acc, cur) => {
if(Array.isArray(cur[0]))
return [...acc, ...cur];
return [...acc, cur];
}, []);

You can convert this like this:
function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
function groupByPairs(arr) {
let result = [];
for (let i = 0; i < arr.length; i += 2) {
result.push([arr[i], arr[i + 1]]);
}
return result;
}
let input = [[1,2],[[3,4],[3,4]],[1,2],[1,2]];
let flat = flatten(input);
let output = groupByPairs(flat);
console.log(output);
And this will give the output [[1, 2], [3, 4], [3, 4], [1, 2], [1, 2]]

Related

Addition of values inside an Array according to certain value [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 14 days ago.
Improve this question
I have an array like this:
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
Expected output:
let expectedOutput = [[0, 1, 6.87], [0, 3, 8.1]];
In this case 4.75 + 2.12 has been summed up because first two values were matching [0, 1].
I want to lookup the first and second value in the sub-array und sum the third value of all the sub-arrays that has the same first and second value. Can you please help me out?
const array = [
[0, 1, 4.75],
[0, 1, 2.12],
[0, 3, 8.1]
];
// groups arrays by first and second item
const groups = {}
for (const [a1, a2, a3] of array) {
if (!(a1 in groups)) {
groups[a1] = {}
}
if (!(a2 in groups[a1])) {
groups[a1][a2] = []
}
groups[a1][a2].push(a3)
}
// sum the third item
const result = []
for (const a1 in groups) {
for (const a2 in groups[a1]) {
const sum = groups[a1][a2].reduce((s, c) => s + c, 0)
result.push([+a1, +a2, sum])
}
}
console.log(result)
When building the result, check if the current element matches a previous one, and then either add only the value or the whole element:
let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
const result = array.reduce( (r, [x,y,v], i) => (i = r.find(e => e[0] === x && e[1] === y), i ? i[2] += v : r.push([x,y,v]), r), [])
console.log(result)

my javascript array is showing 'undefined' after applying a sort function to it. please assist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to do my first ever leetcode challenge. I am failing terribly. I just don't get why my array is showing as undefined here. I am just trying to sort it.
I know there are other ways to sort arrays, but I just can't seem to understand why my sort method here isn't working. i would really appreciate an explanation.
edit: i managed to solve the undefined issue, but now it seems like the array is only storing one single value. is there anything obvious i am doing wrong here?
edit 2: i think the array was only storing 1 single value because I am using 'reduce' here, and thats just the nature of using reduce it seems like. i will try again. thanks for your help guys :)
'use strict';
// define variables
let indexarray, outputarray = [];
const arr1 = [9, 4, 9, 8, 4];
const arr2 = [4, 9, 5];
function arrsort(array) {
const outputz = array.sort(function (a, b) { return a - b });
return outputz;
};
// sort arrays
let arr1s = arrsort(arr1);
let arr2s = arrsort(arr2);
// foreach in arr1, go through arr2 and check if current arr1 array value matches. if yes and current arr2 index val isnt present in 'indexarray', then add current arr2 array val to array 'outputarray' and current index val to 'indexarray'.
arr1s.forEach(function (x, i) {
arr2s.reduce(function (pval, cval, ival) {
if (cval === x && !indexarray.includes(ival)) {
indexarray.push(ival);
outputarray.push(cval);
};
});
});
Updated - final solution shown below was submitted ~noobhuzi
const intersect = function (nums1, nums2) {
// define variables
let indexarray1 = [];
let indexarray2 = [];
let outputarray = [];
const arrsort = function (array) {
return array.sort(function (a, b) { return a - b });
};
// sort arrays &&
let nums1s = arrsort(nums1);
let nums2s = arrsort(nums2);
/* foreach in nums1, go through nums2, check if nums1 val (x) matches nums2 val (pval). if yes and current nums2 index val isnt present in 'indexarray', then add current nums2 array val to array 'outputarray' and current index val to 'indexarray'. */
if (1 <= nums1s.length) {
nums1s.forEach(function (x, i) {
if (nums2s.length <= 1000 && 0 <= x && x <= 1000 && typeof x === "number") {
nums2s.forEach(function (pval, iv) {
if (pval === x && !indexarray2.includes(iv) && !indexarray1.includes(i)) {
indexarray1.push(i);
indexarray2.push(iv);
outputarray.push(pval);
}
});
} else {
console.log("ERROR: some constraint is stopping the code from continuing. please check around ForEach.");
};
});
} else {
console.log("ERROR: nums1s constraint is stopping the code from continuing as its length is less than 1.");
};
console.log("outputarray: " + outputarray);
return outputarray;
};
Your sort function have to return the sorted array. Also the initialization of indexarray is also wrong.
Also you are making use of Array.reduce incorrectly. You just need to have Array.forEach
Updated answer.
// define variables
let indexarray = [];
let outputarray = [];
const arr1 = [9, 4, 9, 8, 4];
const arr2 = [4, 9, 5];
function arrsort(array) {
return array.sort(function (a, b) { return a - b });
};
// sort arrays
let arr1s = arrsort(arr1);
let arr2s = arrsort(arr2);
// foreach in arr1, go through arr2 and check if current arr1 array value matches.
// if yes and current arr2 index val isnt present in 'indexarray',
// then add current arr2 array val to array 'outputarray' and current index val to 'indexarray'.
arr1s.forEach(function (x, i) {
arr2s.forEach(function (pval, i2) {
if (pval === x && !indexarray.includes(i2)) {
indexarray.push(i2);
outputarray.push(pval);
};
});
});
console.log(indexarray);
console.log(outputarray);

Filter list function array java script [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have an array below where I am trying filter for only numbers , however when I use this i still get the strings
function filter_list(l) {
arrs = []
for (var i = 0; i < l.length; i++) {
if (typeof l[i] == 'number');
arrs.push(l[i]);
}
return arrs
}
console.log(
filter_list([1,2,'a','b']), // [1,2]
filter_list([1,'a','b',0,15]), // [1,0,15]
filter_list([1,2,'aasf','1','123',123]), // [1,2,123]
)
However, when i change it to have i not be referencing the index i, when i do
filter_list([1,2,'a','b']) I get [0, 1, 2, 3] instead of [1,2]
function filter_list(l) {
arrs = []
for (var i = 0; i < l.length; i++) {
if (typeof i == 'number');
arrs.push(i);
}
return arrs
}
I'm wondering how it all flow to arrive at this. Thank you in advance!
Your first attempt is correct, but there should not be semicolon after if statement. Try this:
function filter_list(l) {
arrs = []
for (var i = 0; i < l.length; i++) {
if (typeof l[i] === 'number'){
arrs.push(l[i]);
}
}
return arrs
}
console.log(filter_list([1,2,'a','b']))
console.log(JSON.stringify(filter_list([1,2,'a','b'])) === '[1,2]')
console.log(filter_list([1,'a','b',0,15]))
console.log(JSON.stringify(filter_list([1,'a','b',0,15])) == '[1,0,15]')
console.log(filter_list([1,2,'aasf','1','123',123]))
console.log(JSON.stringify(filter_list([1,2,'aasf','1','123',123])) === '[1,2,123]')
Note: you cannot directly compare arrays. You will have to either compare each value or the stringified version.
Also you can use the for/of loop to get the value of each element
var arr = [1, 2, 'a', 'b', 3, 4];
var out = [];
for(let el of arr){
typeof el == 'number' ? out.push(el) : 0;
}
console.log(out);
I hope this helps
var arr = [0, 1, 2, 'a', 'b', 3, 4];
var filtered = arr.filter(x => typeof(x) == 'number');
console.log(filtered);
You need to use 'typeof' and 'filter'. You are getting 0 as you are checking index.
console.log(filter_list([1,2,'a','b']))
console.log(filter_list([1,'a','b',0,15]))
console.log(filter_list([1,2,'aasf','1','123',123]))
function filter_list(l) {
arrs = l.filter(item =>{
return typeof item ==='number';
});
return arrs
}

How to get only values with not duplicated from an array [duplicate]

This question already has answers here:
Javascript remove all occurrence of duplicate element, leaving the only one that is unique
(10 answers)
Closed 3 years ago.
Here is an array : [2,2,3,3,5,7,9,9]
from this array, i needs the values not it doesn't have an duplicate. how to get it?
const onlyUniqueWithoutDup = array.filter((item) => !item.indexOf(array))
looking the result as : [5,7];
any help?
You can use:
const array = [2,2,3,3,5,7,9,9];
const result = array.filter((item, index, arr) => (arr.lastIndexOf(item) == arr.indexOf(item)));
console.log(result);
Create an object where the keys will be the element from this array and then the value will the number of repetition. Then iterate this object and get the keys where value is only 1
let data = [2, 2, 3, 3, 5, 7, 9, 9];
let newData = data.reduce((acc, curr) => {
if (acc[curr]) {
acc[curr] += 1;
} else {
acc[curr] = 1
}
return acc;
}, {});
let nonDup = [];
for (let keys in newData) {
if (newData[keys] === 1) {
nonDup.push(keys)
}
}
console.log(nonDup)

I want to sort the element of array [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 6 years ago.
Improve this question
Suppose I have the array as follows
var array=[3,4,5,5,5,6,8,3,12,1,1,1];
Then the result should be
array=[5,1,3,4,6,8,12];
Required implementation in JavaScript or nodejs
I used a combination of lodash and plain JavaScript array methods in this jsbin example:
var arr = [3,4,5,5,5,6,8,3,12,1,1,1];
var sorted = _.sortBy(_.toPairs(arr.reduce(function(agg, curr) {
agg[curr] = agg[curr] ? agg[curr] + 1 : 1;
return agg;
}, {})), function(pair) {
return -pair[1];
}).map(function(pair) {
return pair[0];
});
console.log(sorted); // => ["1", "5", "3", "4", "6", "8", "12"]
However, the ordering of "5" and "1" is different that the ordering of the 3,4,6,8,12, because the sort order wasn't specified for numbers that have identical counts.
What the above does is created a map of number=>count (e.g. { "1": 3, "5": 3 }), and then pairs them as tuples (since objects can't be sorted deterministically in JavaScript: [["1", 3], ["5", 3]]). Then, we simply sort the collection of tuples based on the count, and map over the collection of tuples to return just the number (e.g. ["1", "5", /* etc. */ ]).
var array = [3, 4, 5, 5, 5, 6, 8, 3, 12, 1, 1, 1];
var obj = {};
array.forEach(e => obj[e] = obj[e] + 1 || 1);
var sorted = Object.keys(obj)
.map(e => ({ n: e, times: obj[e] }))
.sort((a, b) => b.times - a.times)
.map(e => e.n);
document.write(sorted);
Here's one way to do it:
JSBIN: https://jsbin.com/josuwir/1/edit?js,console
var array=[3,4,5,5,5,6,8,3,12,1,1,1];
var c = array.reduce(function(a, b) {
a[b] = ++a[b] || 1;
return a;
}, {});
var keys = Object.keys(c);
var nn = keys.sort(function(a, b) {
if (c[a] < c[b]) {
return 1;
} else {
return -1;
}
}).map(function(a) {return Number(a)});
function sortArray(array) {
var reducedArray = array.filter(function(item, pos) { //A copy without duplicates
return array.indexOf(item) == pos;
})
var elementFreq = {} //Object that contains element frequencies
for (var i=0; i<reducedArray.length; i++) {
var count = 0;
for (var j=0; j<array.length; j++) {
if (array[j] == reducedArray[i]) {
count++;
}
}
elementFreq[array[i]] = count;
}
function compare(a,b) { //compares the frequency of two elements
return elementFreq[b]-elementFreq[a]
}
reducedArray.sort(compare) //sorts reducedArray based using compare function
return reducedArray
}

Categories

Resources