How do I convert an array object into a two-dimensional array - javascript

Here is a Array list.
const list = [
{
id: 5844,
option: 'fruit'
children: ['apple', 'banana', 'pear']
},
{
id: 5845,
option: 'vegetables'
children: ['tomato', 'potato', 'spinach']
}
]
I want to get a new array like this
apple of fruit's children is index 0
tomato of vegetables's children is index = 0
so they are match
[['apple', 'tomato'], ['banana', 'potato'], ['pear', 'spinach']]

With this solution it doesn't matter how many objects are in the array. You can map over the children in the first object and use it's length to return a flatMap of the children elements.
const list=[{id:5844,option:"fruit",children:["apple","banana","pear"]},{id:5845,option:"vegetables",children:["tomato","potato","spinach"]},{id:5846,option:"buildings",children:["church","warehouse","skyscraper"]}];
function getNewData(list) {
// `map` over the children in the first object
// using its index to return a new flattened array
// of all array object children
return list[0].children.map((_, i) => {
return list.flatMap(obj => obj.children[i]);
});
}
console.log(getNewData(list));

I think we can try this piece of code
const list = [
{
id: 5844,
option: 'fruit',
children: ['apple', 'banana', 'pear']
},
{
id: 5845,
option: 'vegetables',
children: ['tomato', 'potato', 'spinach']
}
]
var ans = []
list.forEach(item => {
item.children.forEach((child, index) => {
if (!ans[index]) {
ans[index] = []
ans[index].push(child)
} else {
ans[index].push(child)
}
})
})

I assume your children have same length. We can use 2 loop to group the element of children.
First loop to iterate the element of children.
Second loop to iterate the element of list.
Here is simple code to solve your case.
var listSize = list.length;
var childSize = list[0].children.length;
var expectedArrs = [];
for(var i=0;i<childSize;i++){
var groupByChild = [];
for(var j=0;j<listSize;j++){
groupByChild.push(list[j].children[i]);
}
expectedArrs.push(groupByChild);
}
console.log(expectedArrs);
The result of console:
[["apple", "tomato"], ["banana", "potato"], ["pear", "spinach"]]

It is resolved such that:
const result = []
for(let i = 0; i< List[0].children; i++){
const result1 = []
result1.push(list[0].children[i] )
result1.push(list[1].children[i])
result.push(result1)
}

Related

How to get objects with a common property from an array in lodash?

Hello there good Samaritan, i would like to use Lodash and find the user with most books in the array.
const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ]
Thanks in advance :)
function search_book(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].book === nameKey) {
return myArray[i];
}
}
}
var array = [
{ book:"deep learning", value:"this", other: "that" },
{ book:"ml", value:"this", other: "that" }
];
var resultObject = search_book("ml", array);
console.log(resultObject)
_.filter(list, { name: 'Adam' })
var group = _.countBy(list, function(item){return item.name});
That will get the counts of author in the list, then you can sort and find the one with the largest.
You can generate a function with lodash's _.flow():
Count the objects by the name property
Convert the resulting object of the previous step to [key, value] pairs,
Find the pair with the max value
Get the key (the name)
const { flow, countBy, toPairs, maxBy, tail, head } = _
const fn = flow(
arr => countBy(arr, 'name'), // count by name
toPairs, // convert to [key, value] pairs
arr => maxBy(arr, tail), // find the max by the value (tail)
head // get the key (head)
)
const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ]
const result = fn(books)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And the same idea using Lodash/fp:
const { flow, countBy, toPairs, maxBy, tail, head } = _
const fn = flow(
countBy('name'), // count by name
toPairs, // convert to [key, value] pairs
maxBy(tail), // find the max by the value (tail)
head // get the key (head)
)
const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ]
const result = fn(books)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>

Merge array with underscore by keys

I have 2 arrays :
[{id:1,name:"name"},{id:2,name:"name2"} ,{id:3,name:"name3"}]
[{id:1,date:"123"},{id:2,date:"456"}]
Array 1 should be updated only if the id is equal :
So the array 1 will looks like
It should not create a new array . Only update the array 1 based on array 2
[{id:1,name:"name",date:"123"},{id:2,name:"name2",date:"456"} ,{id:3,name:"name3"}]
I managed to do that with for loop on array2 and inside the for filter like the following :
._filter(array1,function(item){
If(item.id=array2.id)
Do smth and update the array1.date
})
How do I doing that in he best way ? Using underscore.js
You can do something like this:
Iterate over array1 and check if the id of each item exists in array2 by using the some() method.
var arr1 = [{id:1,name:"name"},{id:2,name:"name2"} ,{id:3,name:"name3"}];
var arr2 = [{id:1,date:"123"},{id:2,date:"456"}];
var missing = [];
arr1.forEach( (item1, i) => {
var isExist = arr2.some(item2 => item2.id === item1.id)
if(!isExist) {
missing.push(i);
}
})
missing.forEach(item => {
arr2.push(arr1[item]);
})
console.log(arr2);
reference for some()
Try this :
var a = [{id:1,name:"name"},{id:2,name:"name2"} ,{id:3,name:"name3"}] ;
var b = [{id:1,date:"123"},{id:2,date:"456"}] ;
var i = 0, j = 0 ;
while( i < a.length ) {
j = 0 ;
while( j < b.length) {
if ( a[i].id === b[j].id )
Object.assign( a[i] , b[j] );
j++;
}
i++;
}
console.log(a) ;
You can use forEach to iterate over the second array and use findIndex to get the matched element from first array. If the id matches then update the object in the first array
let arr1 = [{
id: 1,
name: "name"
}, {
id: 2,
name: "name2"
}, {
id: 3,
name: "name3"
}]
let arr2 = [{
id: 1,
date: "123"
}, {
id: 2,
date: "456"
}]
arr2.forEach(function(acc) {
let findArry1Index = arr1.findIndex(function(item) {
return item.id === acc.id;
});
if (findArry1Index !== -1) {
arr1[findArry1Index].date = acc.date;
}
});
console.log(arr1)
You can do it using native language like this:
const arr1 = [{id:1,name:"name"},{id:2,name:"name2"} ,{id:3,name:"name3"}];
const arr2 = [{id:1,date:"123"},{id:2,date:"456"}];
arr1.forEach((ele) => {
const match = arr2.find(item => ele.id === item.id) || {};
Object.assign(ele, match);
});
console.log(arr1);
var a = [{id:1,name:"name"},{id:2,name:"name2"} ,{id:3,name:"name3"}];
var b = [{id:1,date:"123"},{id:2,date:"456"}];
a = _.map(a, function(e) { return _.extend(e, _.findWhere(b, {id: e.id})); });
a results in:
0: {id: 1, name: "name", date: "123"}
1: {id: 2, name: "name2", date: "456"}
2: {id: 3, name: "name3"}
However, I guess this qualifies as "creating a new array"? Maybe it can serve as an inspiration though ¯\_(ツ)_/¯
You can use underscore's indexBy function to index your second array by id, and then simply use Object.assign(...) to update your first array's elements with their corresponding match by performing a lookup in the indexed elements object.
let arr1 = [{id:1, name:"name"}, {id:2, name:"name2"}, {id:3, name:"name3"}]
let arr2 = [{id:1, date:"123"}, {id:2, date:"456"}]
const arr2Groups = _.indexBy(arr2, e => e.id);
arr1.forEach(e => Object.assign(e, arr2Groups[e.id] || {}));
console.log(arr1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Logic for listing out the item from array typescript

Input obj is
let arr1 = [
[[{id:1}, {id:2}],
[{id:3}, {id:4}],
[{id:5}]
]
}
Need a result as following
let op = [{id:1}, {id:3},{id:5},{id:2},{id:4}]
Logic is listing out based on
first item of first array then first item of second array then first item of third array then second item of first array.... it will go like this. N * N array
The answer is the function you are looking for:
"use strict";
function answer(arr) {
let op = [];
let i = 0;
while (true) {
let hasSome = false;
for (const item of arr) {
if (item[i]) {
op.push(item[i]);
hasSome = true;
}
}
if (!hasSome)
return op;
i++;
}
}
const arr1 = [
[{ id: 1 }, { id: 2 }],
[{ id: 3 }, { id: 4 }],
[{ id: 5 }]
];
console.log(answer(arr1));

What is the best way to convert an array of strings into an array of objects in Angular 2?

Let's say I have an array as follows:
types = ['Old', 'New', 'Template'];
I need to convert it into an array of objects that looks like this:
[
{
id: 1,
name: 'Old'
},
{
id: 2,
name: 'New'
},
{
id: 3,
name: 'Template'
}
]
You can use map to iterate over the original array and create new objects.
let types = ['Old', 'New', 'Template'];
let objects = types.map((value, index) => {
return {
id: index + 1,
name: value
};
})
You can check a working example here.
The solution of above problem is the map() method of JavaScript or Type Script.
map() method creates a new array with the results of calling
a provided function on every element in the calling array.
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*map() method creates a new array with the results of calling
a provided function on every element in the calling array.*/
let types = [
'Old',
'New',
'Template'
];
/*
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
*/
let Obj = types.map((value, i) => {
let data = {
id: i + 1,
name: value
};
return data;
});
console.log("Obj", Obj);
Please follow following links:
TypeScript
JS-Fiddle
We can achieve the solution of above problem by for loop :
let types = [
"One",
"Two",
"Three"
];
let arr = [];
for (let i = 0; i < types.length; i++){
let data = {
id: i + 1,
name: types[i]
};
arr.push(data);
}
console.log("data", arr);

How to group and transform dictionary array on a certain key attribute to a different format with javascript (functional programming)?

I'd like to transform the below dataset array into a different format. Currently, each dictionary in the array has a 'count', 'fruit', and 'first name'. I'd like to create a new dictionary for each distinct first name and values that first name has for each 'fruit' type.
For example, see below for some input data
var input_data = [{"count":1,"fruit":"apple","first_name":"abe"},{"count":1,"fruit":"apple","first_name":"bob"},{"count":10,"fruit":"banana","first_name":"bob"},{"count":5,"fruit":"cherry","first_name":"abe"}]
We know for this dataset that the categories are ['apple', 'banana', 'cherry']
var desired_output =
[{name: 'abe',data:[1,0,5]},
{name: 'bob',data:[1,10,0]}]
You could use a hash table for the name reference and an object for the rigth index for counting.
var input_data = [{"count":1,"fruit":"apple","first_name":"abe"},{"count":1,"fruit":"apple","first_name":"bob"},{"count":10,"fruit":"banana","first_name":"bob"},{"count":5,"fruit":"cherry","first_name":"abe"}],
categories = ['apple', 'banana', 'cherry'],
cat = {},
result = [];
categories.forEach(function (a, i) { cat[a] = i; });
input_data.forEach(function (a) {
if (!this[a.first_name]) {
this[a.first_name] = { name: a.first_name, data: categories.map(function () { return 0; }) };
result.push(this[a.first_name]);
}
this[a.first_name].data[cat[a.fruit]] += a.count;
}, Object.create(null));
console.log(result);

Categories