I have two arrays both consisting of 30 items.
Array 1: [ {cat, red} , {dog, blue} , ... ]
Array 2: [ {1}, {2}, ... ]
My goal is to have Array 3 like so:
[ {Cat, red, 1} , {dog, blue, 2} ... ]
I am using JavaScript and cheerio to grab the data.
Your objects look strange, {1} isn't a valid object. Maybe you meant something like {id: 1}?
Anyway, looks like you need something like this:
const arr3 = arr1.map((el, index) => {
return {
...el,
...arr2[index],
}
})
It's hard to tell what the data actually looks like, since [ {cat, red} , {dog, blue} , ... ] isn't valid JSON or anything, but the general idea would be to get the corresponding element from the other array by index, either using .map((el, index) => { // ... }) or just looping over it, so something like:
const arr1 = [{title: 'movieA', rank: '1' }, {title: 'MovieB', rank: '2'}]
const arr2 = [{score: 10}, {score: 20}]
console.log(arr1.map((el, i) => {
return { ...el, ...arr2[i] }
}));
Related
Right now I need to merge the string into one.
This is my try ->
After this merge i got example of array ->
[
[{id: 1, name: "One"}],
[{id: 2, name : "two"}]
]
problem is newData because always print new array.
I need to data be like ->
[
{id: 1, name: "One"},
{id: 2, name : "two"}
]
What i am try, with foreEach ->
newState((oldData) => [...oldData, newData.forEach((new) => new)]);
No work.
Also what I am try
let filteredArray = newData.map(data => data);
Also no work, why?
Every time I get new information inside array newData....
I need solution to get only result inside array and print to
newState((oldData) => [...oldData, newResultWhichIsObject]);
Also some time my newData have few object inside array
The map method isn't the right method to use in your case. Map method will take as an entry an array of n elements and mutate it into an array of n element, on which an operation was applied. See MDN documentation
You should use the reduce method, which provides the ability to construct a brand new array from an empty one, here is the snippet :
const baseArray = [
[{id: 1, name: "One"}],
[{id: 2, name : "two"}]
];
const flattenedArray = baseArray.reduce((acc, curr) => ([...acc, ...curr]), []);
// For demo purpose, console.log
console.log(flattenedArray);
Reduce array method is a bit tricky, that is why I invite you to read the documentation carefully and play with it.
You can use .flat() method. Try this
const newData = [
[{id: 1, name: "One"}],
[{id: 2, name : "two"}]
];
console.log(newData.flat())
I have two arrays
arrayOfItems: [
{
id: '4321-3321-4423',
value: 'some text'
},
{
id: '4322-4654-9875',
value: 'some text again'
}
]
Then the second array
itemX: [
{
id: '3214-6543-4321',
nestedArrayOfItems:[
{id: '4321-3321-4423'}
{id: '3455-8765-7764'}
]
}
]
I need to create a new array based on arrayOfItems that doesn't include any of the id's in the itemX.nestedArrayOfItems
Because of it being a nested Array I'm drawing a blank on what I need to do... I'm searching through Lodash to see if there is something that doesn't involve me using a bunch of for loops.
You can use Array.prototype.filter() and then check if the id exists with
Array.prototype.some() like so:
const arrayOfItems = [
{
id: '4321-3321-4423',
value: 'some text'
},
{
id: '4322-4654-9875',
value: 'some text again'
}
]
const itemX = [
{
id: '3214-6543-4321',
nestedArrayOfItems: [
{id: '4321-3321-4423'},
{id: '3455-8765-7764'}
]
}
]
const res = arrayOfItems.filter(item => !itemX[0].nestedArrayOfItems.some(({ id }) => id === item.id))
console.log(res);
how about this :
let difference = arrayOfItems.filter(x => ! itemX.nestedArrayOfItems.includes(x));
PS : ids must be string
I have an array containing objects that every element but the last one are objects, but I want to convert them into an array of arrays and add the last element.
To be more explicit here is how I have it:
[
{ 0: [1,2], 1: [6,2], name: "" },
{ 0: [3,4], 1: [2,2], name: "" }
]
and the result I want is this one:
[
{ multipolygon: [ [1,2], [6,2] ], name: ""},
{ multipolygon: [ [3,4], [2,2] ], name: ""}
]
Each single array contained inside the original array is converted into an array of those arrays.
I have tried doing this:
const zonesArray = zones.map(el => Object.values(el)) // obj => array
const polygons = zonesArray.filter(el => el.pop()) // array without name
to get all the arrays contained inside the obj but then I realized how can I replace this into the original objects.
I have tried to modify the groupBy function found on MDN:
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
}, {})
}
But I can't seem to find the answer
It doesn't look like you're trying to group by a property, you're trying to transform each object in the array separately - which can be done by taking the name and the numeric properties together when mapping, then returning the shape of the new object:
const arr = [
{ 0: [1,2], 1: [6,2], name: "" },
{ 0: [3,4], 1: [2,2], name: "" }
];
const result = arr.map(({ name, ...rest }) => ({
name,
multipolygon: Object.values(rest)
}));
console.log(result);
Are the steps I'm taking to solve this problem correct?
I'm working on turning a data structure of an array of arrays such as
this.arrayofAnimalsAndValues = [
[ "Ant", 1287, 12956],
[ "Lion", 2574, 25826],
[ "Bear", 3861, 38696],
.....
]
into this
this.jsonOfAnimalsAndValues = [
{category: "Ant", value_1: 1287, value_2:12956},
{category: "Lion", value_1: 2574, value_2:25826},
{category: "Bear", value_1: 3861, value_2:38696},
.....
]
where the first item in the array is always assigned to 'category' in the array object and the following items assigned to value_# depending on their order in the array. So the 2nd array item would have key value_1 and so on. For example, for 1 nested array:
[[ "Ant", 5148, 51566]] to =>
[{category: "Ant", value_1: "5148", value_2: 51566}]
I've created a hardcoded way to achieve this however I'm trying to make it dynamic:
'hardcoded' way:
this.variableOfKeys = ["value_1", "value_2", "value_3", ......]
this.jsonOfAnimalsAndValues = this.arrayofAnimalsAndValues(function(x) {
return {
category: x[0],
no1: x[1],
no2: x[2],
.....
};
});
where I just hardcode the keys and their values (values using their index).
My attempt to make it dynamic:
this.variableOfKeys.forEach(element => {
this.jsonOfAnimalsAndValues = this.arrayofAnimalsAndValues.map(function(x) {
for (var i = 0; i<=this.arrayOfValuesToUseAsKeys.length; ++i) {
return {
category: x[0],
element: x[i+1],
};
}
});
});
where my logic is that for each item in
this.variableOfKeys = ["value_1", "value_2", "value_3", ......],
I created this.jsonOfAnimalsAndValues such that the first item (item with the 0th index) in the array this.arrayofAnimalsAndValues is assigned to the key category and the following items (depending on their index) are assigned to the values in this.variableOfKeys in order starting from no1, then no2 etc.
However, I don't think this is written correctly and I keep getting this error:
"TypeError: Cannot read property 'variableOfKeys' of undefined"
Can I ask how it might be written incorrectly and so how I might be able to create this.jsonOfAnimalsAndValues from this.arrayofAnimalsAndValues?
You can map each subarray to an array of entries, then turn it into an object to return with Object.fromEntries:
const arrayofAnimalsAndValues = [
[ "Ant", 1287, 12956],
[ "Lion", 2574, 25826],
[ "Bear", 3861, 38696],
];
const output = arrayofAnimalsAndValues.map(
([category, ...rest]) => Object.fromEntries([
['category', category],
...rest.map((value, i) => ['value_' + (i + 1), value])
])
);
console.log(output);
Given an array of the keys you can map() the main array and use reduce() on each subarray to generate each object
const arr=[["Ant",1287,12956],["Lion",2574,25826],["Bear",3861,38696]],
keys = ['category','value_1','value_2'];
const res = arr.map(e => e.reduce((a,c,i) => (a[keys[i]] = c, a),{}))
console.log(res)
.as-console-wrapper { max-height: 100%!important;top:0}
what i need is to transform this Array
[
0: {id: 1},
1: {id: 2}
]
to
[
1: {id: 1},
2: {id: 2}
]
Just switching keys I suppose, Im trying to use .map but all i can change are the values not the keys
I think you can solve it easily enough with reduce
It starts with an empty array, and during each iteration 1 item is added, at the index of the items id field.
This will give you an array with a length that might not be what you have expected, so I would suggest to look a bit deeper into your requirements.
var arr = [
{id: 1},
{id: 2}
];
var result = arr.reduce( (container, item) => {
container[item.id] = item;
return container;
}, [] );
console.log( result[1] );
console.log( result[2] );
console.log( result );
You could always make it an object with the correct keys, with pretty much the same syntax
var arr = [
{id: 1},
{id: 2}
];
var result = arr.reduce( (container, item) => {
container[item.id] = item;
return container;
}, {} );
console.log( result[1] );
console.log( result[2] );
console.log( result );
And important thing to note, is that with the array, you have an undefined value at position 0, the object version doesn't have it. It would make more sense to use the object version, and not the array. As mentioned in the comments, it's not a very good idea to have gaps in your array.