Seperate values based on property value and show with javascript - javascript

I have an array that looks like this:
var array = [[
{ "loc": {} },
{ "distance": 6.4 },
{ "zip1": "06120" },
{ "zip2": "06095" },
{ "group": 1 },
{ "weight": 1119 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 2 },
{ "weight": 41976 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 1 },
{ "weight": 41976 }
]];
Now I want to take the array values based on the property values for show in HTML.
Expected output is split into array with "group" property. I also need to store in HTML with based on group, as shown in the example below:
group 1:
all zip1's under group 1
group 2:
all zip1's under group 2
I tried using a loop but I didn't manage to get the right answer:
for (var k = 0; k < array.length; k++) {
var array1 = array[k];
if (flag[array1[2]["zip1"]]) continue;
flag[array1[2]["zip1"]] = true;
output2.push(array1);
}
So help me to find split the array show in HTML with group wise

Using reduce, you can create an object with each group value as key and an array of zip1 as values like this:
Then loop through the Object.entries, to create the HTML:
const array = [[{"loc":{}},{"distance":6.4},{"zip1":"06120"},{"zip2":"06095"},{"group":1},{"weight":1119}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":2},{"weight":41976}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":1},{"weight":41976}]];
const merged = array.reduce((r, a) =>{
const { group } = a.find(n => n.group)
const { zip1 } = a.find(n => n.zip1)
r[group] = r[group] || []
r[group].push(zip1)
return r;
},{})
const output = document.getElementById('output');
Object.entries(merged).forEach(([group, zips]) => {
const h1 = document.createElement('h1');
h1.innerHTML = "group " + group
const span = document.createElement('span');
span.innerHTML = `Zip1 - ${zips} (in group - ${group})`;
output.appendChild(h1)
output.appendChild(span)
})
<div id="output"></div>

Related

Building a table from an array in React

I have an array stating salary of different sectors. I need to calculate and then create a table based on this . I'm really confused how to do it . Here is an example data
const data=[
['Euro','Tech'],
['USD','Tech'],
['GBX', 'Health'],
['Euro', 'Real Estate'],
['GBX', 'Real Estate'].
]
Now I have to display the sector ,salary & total in the Table like this below:
Sector
Euro
GBX
USD
Total
Tech
1
0
1
2
Health
0
1
0
1
Real Estate
1
1
0
2
Total
2
2
1
5
Could you help me with this. I'm using React table to display the data.
Here the idea is to create a two dimensional array filled with zeros, then work through each item in the data array and increment the correct value in the two diminsional array based on a lookup using a map of sector names to indexes and a map of currency names to indexes.
Hopefully it helps, though I feel like there's probably a better way to do it.
const data = [
['Euro','Tech'],
['USD','Tech'],
['GBX', 'Health'],
['Euro', 'Real Estate'],
['GBX', 'Real Estate'],
['GBX', 'Health'],
];
const array_unique = (arr) => Array.from(new Set(arr));
const sectors = array_unique( data.map(([_, sector]) => sector) );
const currencies = array_unique( data.map(([currency]) => currency) ).sort();
const sector_map = Object.fromEntries(
sectors.map((sector, index) => [sector, index])
);
const currency_map = Object.fromEntries(
currencies.map((currency, index) => [currency, index])
);
// zero fill 2 dimensional array
const values_matrix = sectors.map( () => currencies.map(() => 0) );
// increment values in the 2 dimensional array for each item in the data array
// getting the row index and column index from the sector_map and currency_map
for(const [currency, sector] of data) {
values_matrix[ sector_map[sector] ][ currency_map[currency] ]++;
}
// create rows for a table
const rows = [['Sector', ...currencies]];
for(const [index, sector] of sectors.entries()) {
rows.push([sector, ...values_matrix[index]]);
}
console.log(rows.map((row) => row.join(',')));
try this code to format data array
const data = [
['Euro', 'Tech'],
['USD', 'Tech'],
['GBX', 'Health'],
['Euro', 'Real Estate'],
['GBX', 'Real Estate'],
];
let res = {};
let currencies = [];
data.map((item) => {
const [val, key] = item;
res[key] ? res[key].push(val) : (res[key] = [val]);
if (!currencies.includes(val)) currencies.push(val);
});
const rows = Object.keys(res); //Tech, Health, Real Estate
const table = new Array(rows.length);
let index = 0;
for (let row = 0; row < currencies.length; row++) {
key = rows[row];
const values = Object.values(res[key]);
table[index] = { title: key, values: new Array(currencies.length) };
for (let i = 0; i < currencies.length; i++) {
const element = currencies[i];
if (values.includes(element)) {
table[index].values[i] = { title: element, value: 1 };
} else {
table[index].values[i] = { title: element, value: 0 };
}
}
index++;
}
console.log(JSON.stringify(table, null, 2));
result will be like this
[
{
"title": "Tech",
"values": [
{
"title": "Euro",
"value": 1
},
{
"title": "USD",
"value": 1
},
{
"title": "GBX",
"value": 0
}
]
},
{
"title": "Health",
"values": [
{
"title": "Euro",
"value": 0
},
{
"title": "USD",
"value": 0
},
{
"title": "GBX",
"value": 1
}
]
},
{
"title": "Real Estate",
"values": [
{
"title": "Euro",
"value": 1
},
{
"title": "USD",
"value": 0
},
{
"title": "GBX",
"value": 1
}
]
}
]

Get parent object after looping through nested array

I have a nested array I loop through every element in the array and read the value of key title then I check if the value includes a certain string if it includes the search string that value will be pushed to another array then I sort the new array by occurrence of the search string so that the index position of every element in the new array depends how similar the array element string is with the search string and also the array elements will be sorted by ascending letter order. Now this whole procedure works fine. What I want is once I get the sorted new array I want to loop though it then get the object containing the new arrays element as a title. How can I achieve this. Read the comments in my code to better understand my question. Thanks in advance.
note: When retrieving the object it should keep the index position of the newly created array.
const allArr = [
[{
"id": "1",
"title": "blaha"
}, {
"id": "2",
"title": "blahe"
}, {
"id": "3",
"title": "dhs"
}],
[{
"id": "4",
"title": "blahc"
}, {
"id": "5",
"title": "shg"
}]
]
const searchTerm = 'blah'
let existsArr = []
let tempArr = []
for (var i = 0; i < allArr.length; i++) {
const allAds = allArr[i]
for (var j = 0; j < allAds.length; j++) {
if (allAds[j].title.toLowerCase().includes(searchTerm.toLowerCase())) {
existsArr.push(allAds[j].title)
}
}
}
tempArr = existsArr.filter(a => a.toLowerCase().includes(searchTerm))
const startsWith = (string, value) => string.substring(0, value.length).toLowerCase() === value
const sortByOccurance = JSON.stringify(tempArr.sort((a, b) => {
const aStartsWith = startsWith(a, searchTerm)
const bStartsWith = startsWith(b, searchTerm)
if (aStartsWith && !bStartsWith) {
return -1
} else if (!aStartsWith && bStartsWith) {
return 1;
}
return b > a ? -1 : 1
}))
console.log(sortByOccurance)
//now I want to get the object of every title found in sortByOccurance from allArr
//expected output:
//[{"id": "1", "title": "blaha"}, {"id": "4", "title": "blahc"}, {"id": "2", "title": "blahe"}]
Array.flat flattens the array a level (or more). That makes it easier to find an item.title === term. So now we can loop over array and build our result array.
Update: not using Array.flat to allow for duplicate names with different id. Instead, we search for the first match (a "deep" search) and then delete it so next time will find next item.
const allArr = [
[{
"id": "1",
"title": "blaha"
}, {
"id": "2",
"title": "blahe"
}, {
"id": "3",
"title": "dhs"
}],
[{
"id": "4",
"title": "blahc"
}, {
"id": "5",
"title": "shg"
}],
[{
"id": "6",
"title": "blaha"
}]
]
const searchTerm = 'blah'
let existsArr = []
let tempArr = []
for (var i = 0; i < allArr.length; i++) {
const allAds = allArr[i]
for (var j = 0; j < allAds.length; j++) {
if (allAds[j].title.toLowerCase().includes(searchTerm.toLowerCase())) {
existsArr.push(allAds[j].title)
}
}
}
tempArr = existsArr.filter(a => a.toLowerCase().includes(searchTerm))
const startsWith = (string, value) => string.substring(0, value.length).toLowerCase() === value
const sortByOccurance = JSON.stringify(tempArr.sort((a, b) => {
const aStartsWith = startsWith(a, searchTerm)
const bStartsWith = startsWith(b, searchTerm)
if (aStartsWith && !bStartsWith) {
return -1
} else if (!aStartsWith && bStartsWith) {
return 1;
}
return b > a ? -1 : 1
}))
function find_deep(arr, term) {
for (var i = 0; i < arr.length; i++) {
var value = arr[i]
if (Array.isArray(value)) {
var res = find_deep(value, term)
if (res) {
return res;
}
}
if (value.title === term) {
return value;
}
}
return null;
}
console.log(sortByOccurance)
var result = [];
JSON.parse(sortByOccurance).forEach(function(term) {
var found = find_deep(allArr, term)
if (found) {
result.push({ ...found
})
delete found.title; // <--- changes original allArr.
}
})
console.log(result)
.as-console-wrapper {
max-height: 100% !important
}

JavaScript: take properties from multiple objects and assign to one

So im working with an array of objects that requires data from multiple objects to be put into one dependant on the date within those objects.
The starting object looks like this:
[
{
"LOCATION":17,
"Stock_In_Area":39.0709838867,
"DATE_DT":"2021-03-07",
},
{
"LOCATION":17,
"Stock_In_Area":41.8843955994,
"DATE_DT":"2021-03-14",
},
{
"LOCATION":612,
"Stock_In_Area":8.4867076874,
"DATE_DT":"2021-03-07",
},
{
"LOCATION":612,
"Stock_In_Area":9.2035646439,
"DATE_DT":"2021-03-14",
},
];
and im trying to get something like this:
{
"17":39.0709838867,
"612":8.4867076874,
"date":"2021-03-07",
},
{
"17":41.8843955994,
"612":9.2035646439,
"date":2021-03-14
},
So the object would be
{
[location]: stock_in_area
date: DATE_DT
}
where the two locations have the same date value
I would have maintained a hash kind of variable in memory and compared each item from array wrt to the value present in the hash.
let ip = [{
"LOCATION": 17,
"Stock_In_Area": 39.0709838867,
"DATE_DT": "2021-03-07",
},
{
"LOCATION": 17,
"Stock_In_Area": 41.8843955994,
"DATE_DT": "2021-03-14",
},
{
"LOCATION": 612,
"Stock_In_Area": 8.4867076874,
"DATE_DT": "2021-03-07",
},
{
"LOCATION": 612,
"Stock_In_Area": 9.2035646439,
"DATE_DT": "2021-03-14",
},
];
const _enum = {};
const op = [];
for (let i = 0; i < ip.length; i++) {
let _k = ip[i].DATE_DT;
if (!_enum[_k]) {
_enum[_k] = _k;
op.push({
date: _k,
[ip[i].LOCATION]: ip[i].Stock_In_Area
});
} else {
const found = op.find(el => el.date === _k);
found[ip[i].LOCATION] = ip[i].Stock_In_Area;
}
}
console.log(op);

Push items in an array in Javascript?

I'm working on school-app. person enter students marks from frontend and I've to store it in my backend. I know my data-structure is quite bad. but this is only way I can comfortly use and fit it in my front end application/website.
codeSandbox link
Full Code:
//This data is already set need to push information in this array.
let student = [{
"detail": {
"name": "Mark",
"surname":"widen"
},
}];
//formatting the query in json.
const keys = Object.keys(query)[0].split(",")
const values = Object.values(query)[0].split(",")
const newObj = {}
for (let i = 0; i < keys.length; i++) {
newObj[keys[i]] = values[i]
}
// I've to push it along with "academic-year". so,
for (let a = 0; a < newObj.length; a++) {
const year = a + "st-Year"
console.log(year) // Expected Output: 1st-Year and 2nd-Year
}
// How to run this both for-loop synchronously way ?? AND
//pushing with "ObtainedMarks" and "year" (Error over here)
student.push({
ObtainedMarks: {
year : [
{ physics: newObj }
],
year : [
{ physics: newObj }
]
}
})
console.log(student) //Here's I want expected Output
Expected Output:
let student = [{
"detail": {
"name": "Mark",
"surname":"widen"
},
ObtainedMarks: {
"1st-Year": [
{ physics: { "marks": "500" } } //Physics subject is default.
],
"2nd-Year": [
{ physics: { "mark": "200" } } //Physics subject is default.
]
}
}];
I want to push returned data in student array. with 1st-Year
and 2nd-Year's for-loop.
You can do the conversion in your for-loop
let student = [{
"detail": {
"name": "Mark",
"surname": "widen"
},
}];
let query = {
"marks,mark": "500,200"
}
const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");
const marks = {}
for (let i = 0; i < keys.length; i++) {
marks[i === 0 ? `${i+1}st-year` : `${i+1}nd-year`] = [{
physics: {
[keys[i]]: values[i]
}
}];
}
student.push({
obtainedMarks: marks
});
console.log(student);
Alternative way: map through the keys and create an object from entries after manipulating the data.
let student = [{
"detail": {
"name": "Mark",
"surname": "widen"
},
}];
let query = {
"marks,mark": "500,200"
}
const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");
const marks = Object.fromEntries(keys.map((k, i) => {
return [
i === 0 ? `${i+1}st-year`: `${i+1}nd-year`,
[{ physics: { [k]: values[i] }}]
];
}));
student.push({
obtainedMarks: marks
});
console.log(student);

How to convert Nested array object to a flat table angularjs dynamically using recursive function?

Here is the Nested array Object example. How to recursively append parent elements to the child elements of table?
Please note: there can be n number of levels in nested objects
var data = {
"grandparent_id": 7,
"parents": [
{
"parent_id": 65,
"children": [
{
"child_id": 365
}
]
},
{
"parent_id": 66,
"children": [
{
"child_id": 365
},
{
"child_id": 366
},
{
"child_id": 367,
"smallchildren": [
{
"smallchild_id": 465
},
{
"smallchild_id": 466
},
{
"smallchild_id": 467
}
]
}
]
}
]
}
Expected Output:
var resultArray = [[7,65,365],[7,66,365],[7,66,366],[7,66,367]]
Grandparent_id|parent_id|child_id
7 |65 |365
7 |66 |365
7 |66 |366
7 |66 |367
Tried this:
function normalize(parent) {
if (parent && parent.children) {
for (var i = 0, l = parent.children.length; i < l; ++i) {
var child = parent.children[i];
child.index = i;
if (!child.parentId) child.parentId = parent.id || '0';
normalize(child);
}
}
}
Seems a pretty simple map/reduce job. Simply iterate the parents array and map the children array into an array of data.grandparent_id, parent.parent_id and child.child_id.
const data = {"grandparent_id":7,"parents":[{"parent_id":65,"children":[{"child_id":365}]},{"parent_id":66,"children":[{"child_id":365},{"child_id":366},{"child_id":367}]}]}
const resultArray = data.parents.reduce((arr, parent) => {
return arr.concat(parent.children.map(child =>
[data.grandparent_id, parent.parent_id, child.child_id]))
}, [])
console.info('resultArray =', JSON.stringify(resultArray))
If you want the inner arrays to be objects instead, simply change the map return value...
const data = {"grandparent_id":7,"parents":[{"parent_id":65,"children":[{"child_id":365}]},{"parent_id":66,"children":[{"child_id":365},{"child_id":366},{"child_id":367}]}]}
const resultArray = data.parents.reduce((arr, parent) => {
return arr.concat(parent.children.map(child => ({
grandparent_id: data.grandparent_id,
parent_id: parent.parent_id,
child_id: child.child_id
})))
}, [])
console.info('resultArray =', resultArray)

Categories

Resources