I have a 2D array that I'm mapping in jsx
I am trying to access the outer array index inside the second mapping func
Any ideas would be much appreciated
Something like this:
let arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
{arr.map((innerArr, idx) => {
return innerArr.map((item) => {
return (
<p>
{idx}: {item}
</p>
);
});
})}
Related
I have an array of arrays of Int and I want to sum every value within all the values in the same position in a performing way. For example:
let array: [[Int]] = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
The result should be:
let result: [Int] = [11, 14, 11, 9]
If this is too complex, I can make all subarrays to have the same amount of elements.
My current soultion is the following but I believe it has to be a cleaner and more efficient way of doing it:
func sumElementsInSubArrays(_ array: [[Int]]) -> [Int] {
var result: [Int] = []
for subarray in array {
for (i, value) in subarray.enumerated() {
if result.count > (i) {
result[i] = result[i] + value
} else {
result[i] = value
}
}
}
return result
}
There may be several ways like HOF to deal with this situation but if you are new to it like me , you can do it like this :
Considering all the subArrays to have same number of element :
let array = [[1, 2, 3, 4], [5, 2, 7, 0] , [1, 7, 9, 4]]
var finalArray = [Int]()
for i in 0..<(array.first?.count ?? 0) {
var aElement = 0
array.forEach { aArray in
aElement += aArray[i]
}
finalArray.append(aElement)
}
//Final array should look like this at this point : [7, 11, 19, 8]
You could use a couple of nested loops (I don't think performance wise using reduce would be faster, thought it may look better/debatably be better for readability):
func sumElementsInSubArrays(_ array: [[Int]]) -> [Int] {
var result: [Int] = []
for subarray in array {
for (i, value) in subarray.enumerated() {
if result.count > i {
result[i] += value
} else {
result.append(value)
}
}
}
return result
}
print(sumElementsInSubArrays([[1, 2, 3], [4, 5], [6, 7, 8, 9]]))
print(sumElementsInSubArrays([]))
print(sumElementsInSubArrays([[]]))
Output:
[11, 14, 11, 9]
[]
[]
I am tring to use react-charts and the object they give as example data looks like this.
chartData: [
{
label: 'Series 1',
data: [
[0, 1],
[1, 2],
[2, 4],
[3, 2],
[4, 7],
],
},
],
I want to build my own "data" and replace this temporary data but the whole object of arrays in objects in arrays (Or whatever it is confuses me.
Can someone explain the nesting here.
Is it an array of 2 objects label and data and data` is an array of key value pairs. Is that accurate?
I'm kind of trying something like this...
let myData = []
res.data.payload.forEach(function (item, index) {
console.log(item, index)
myData[(index, item.odds)]
})
this.setState({ chartData[data]: myData })
Am I even close?
Thanks
You can do like this
let myData = []
res.data.payload.forEach(function (item, index) {
console.log(item, index)
myData.push([index, item.odds])
})
this.setState({ chartData: [{...this.state.chartData[0], data: myData}] })
I'm having an object like this
{
"GroupA": {
"Parent1": [1, 2, 3],
"Parent2": [1, 2, 3],
"Parent12": [1, 2, 3]
},
"GroupB": {
"Parent13": [1, 2, 3],
"Parent5": [1, 2, 3]
},
"GroupC": {
"Parent7": [1, 2, 3]
}
}
Now i want to filter this object by searching the name of the Parent
For example when I search parent1 the result should be
{
"GroupA": {
"Parent1": [1, 2, 3],
"Parent12": [1, 2, 3]
},
"GroupB": {
"Parent13": [1, 2, 3],
}
}
Here is my solution but it's not working correctly if a Group has many similar Parent name it only return the first one. And when I try to set state it filter like all wrong value
let newData = []
let catalogArr = Object.entries(catalogList)
const handleSearchElement = (e) => {
const value = e.target.value
catalogArr.forEach(catalog => {
let filteredKeys = Object.keys(catalog[1]).filter(name => name.toLowerCase().includes(value.toLowerCase()))
let valuesOfKey
if(filteredKeys[0]) {
valuesOfKey = {
[filteredKeys[0]]: Object.values(catalog[1][filteredKeys[0]])
}
newData.push([catalog[0], {...valuesOfKey}])
}
})
console.log(Object.fromEntries(newData));
setCatalogList(Object.fromEntries(newData))
// console.log(catalogList);
}
You can use Array#reduce to accomplish this pretty easily, however, all of the packing and unpacking of objects using Object.entries and Object.fromEntries to essentially treat them as arrays suggests you may be using the wrong data structure.
If you need to do this repeatedly, look into doing a one-off transformation that arranges the data for O(1) access, for example, by grouping on inner keys rather than outer keys (hard to say since I don't know the data or use case). Or, if you're mostly iterating, consider using arrays.
const data = {
"GroupA": {
"Parent1": [1, 2, 3],
"Parent2": [1, 2, 3],
"Parent12": [1, 2, 3]
},
"GroupB": {
"Parent13": [1, 2, 3],
"Parent5": [1, 2, 3]
},
"GroupC": {
"Parent7": [1, 2, 3]
}
};
const targetKey = "parent1";
const res = Object.entries(data).reduce((a, [k, v]) => {
const filtered = Object.entries(v).filter(([k, ]) =>
k.toLowerCase().includes(targetKey.toLowerCase())
);
if (filtered.length) {
a[k] = Object.fromEntries(filtered);
}
return a;
}, {});
console.log(res);
I have six items in my array: [1, 2, 3, 4, 5, 6]. I would like to group array items per 3 items like that: [[1, 2, 3], [4, 5, 6]]. Is it possible with underscore?
You can use array#reduce to group your array element.
const arr = [1, 2, 3, 4, 5, 6],
group = 3,
result = arr.reduce((r,v,i) => {
let index = Math.floor(i/group);
(r[index] = r[index] || [])[i%group] = v;
return r;
},[]);
console.log(result);
I'm working on this problem from FreeCodeCamp in JS.
Basically I need to find the difference between two arrays and then return an array with those values i.e. strings and integers.
function diffArray(arr1, arr2) {
//console.log(arr1.length);
var newArr = [];
var dummy = [];
for (var x=0;x<arr1.length;x++) {
if (arr2.indexOf(arr1[x]) === -1) {
newArr = newArr.concat(arr1.slice(x));}}
for (var y=0;y<arr2.length;y++) {
if (arr1.indexOf(arr2[y]) === -1 && newArr.indexOf(arr2[y]) === -1) {
newArr = newArr.concat(arr2.slice(y));
}
}
console.log(newArr);
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
It almost works. Except these do not work:
[1, 2, 3, 5], [1, 2, 3, 4, 5] - Gives [4, 5].
["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite",
"andesite", "grass", "dirt", "dead shrub"] - Gives ["pink wool",
"dead shrub"].
These work though:
[1, "calf", 3, "piglet"], [1, "calf", 3, 4]
[], ["snuffleupagus", "cookie monster", "elmo"]
why are you using slice and concat to feed your output array ?
iterate through arr1
if arr1 has an element which is not in arr2 push it to newArr
iterate though arr2
if arr2 has an element which is not in arr1 push it to newArr
return newArr