javascript overwrite previous element added to array - javascript

When i push into my array, it overwrite the last element added.
Here is my code:
const array = [{ name: [] }];
const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));
array.forEach((obj) => {
ways.forEach((element) => {
obj.item = [{ result: element }];
});
});
The output i get :
[
{
"name": [],
"item": [{ "result": "result3" }]
}
]
The output i want :
[
{
"name": [],
"item": [
{ "result": "result1" },
{ "result": "result2" },
{ "result": "result3" }
]
}
]

const array = [{ name: [] }];
const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));
array.map((obj) => {
obj.item = [];
ways.map((element) => {
obj.item .push([{ result: element }]);
});
});
console.log(array);

You have to declare obj.item as an array and instead of equating values you should push them in the array
const array = [{
name: []
}];
const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));
array.forEach((obj) => {
obj.item = [];
ways.forEach((element) => {
obj.item.push({
result: element
});
});
});
console.log(array)

Using reduce method
const test = `result1
result2
result3`;
const res = test.split(/[\n\r]+/).map(aaa => (aaa)).reduce((all, acc) => {
const [a] = all
a.item.push({
"result": acc
})
return all
}, [{
name: [],
item: []
}])
console.log(res)

Related

How to make a array from another array with grouping data based on id .?

I have an array object as follows,
const data = [
{
"order_id":"ORDCUTHIUJ",
"branch_code":"MVPA",
"total_amt":199500,
"product_details":[
{
"image":"CC252.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORHOGFD79L",
"branch_code":"PBVR",
"total_amt":325880,
"product_details":[
{
"image":"1617382086515.jpg",
"cate":"Mobile Accessories"
},
{
"image":"1617382322759.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC251.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORIYDJLYSJ",
"branch_code":"MVPA",
"total_amt":1549500,
"product_details":[
{
"image":"CC250.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC256.jpg",
"cate":"Mobile Accessories"
}
]
}
]
what I want to achieve is to build a new array based on this, but I want to group the data with the same branch code under one object.
Expected Output:
const newData =
[
{
MVPA: [
{
order_id: 'ORIYDJLYSJ',
(otherdetails)
},
{
order_id: 'ORDCUTHIUJ',
(otherdetails
}
]
},
PBVR: [
{
order_id: 'ORHOGFD79L',
(otherdetails)
}
]
can someone help me out on how to achieve this.? I want a general solution, bcoz this data could be longer than this when I get from DB.
You can do it with Array.reduce.
data.reduce((o, a) => (o[a.branch_code] = [ ...(o[a.branch_code] || []), a], o), {})
First create an object which collects data with branch_code.
const obj = data.reduce((map,obj)=>{
if(obj.branch_code in map){
map[obj.branch_code].push({...obj})
}
else{
map[obj.branch_code]=[{...obj}]
}
return map
},{})
This gives
{MVPA: Array(2), PBVR: Array(1)}
Then,map over the keys of the above object to create your required array.
const result = Object.keys(obj).map(key => ({[key]:
[...obj[key]]}))
console.log('result',result)
This gives
(2) [{…}, {…}]
0: {MVPA: Array(2)}
1: {PBVR: Array(1)}
const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))] // Get unique branch_code
const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order)) // Filter to group together by branch_code
.map(item => ({[item[0].branch_code]: item})) // Assign key and return elements
const data = [
{
"order_id":"ORDCUTHIUJ",
"branch_code":"MVPA",
"total_amt":199500,
"product_details":[
{
"image":"CC252.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORHOGFD79L",
"branch_code":"PBVR",
"total_amt":325880,
"product_details":[
{
"image":"1617382086515.jpg",
"cate":"Mobile Accessories"
},
{
"image":"1617382322759.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC251.jpg",
"cate":"Mobile Accessories"
}
]
},
{
"order_id":"ORIYDJLYSJ",
"branch_code":"MVPA",
"total_amt":1549500,
"product_details":[
{
"image":"CC250.jpg",
"cate":"Mobile Accessories"
},
{
"image":"CC256.jpg",
"cate":"Mobile Accessories"
}
]
}
]
const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))]
const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order))
.map(item => ({[item[0].branch_code]: item}))
console.log(newData)
You can try this way
const data =[{"order_id":"ORDCUTHIUJ","branch_code":"MVPA","total_amt":199500,"product_details":[{"image":"CC252.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORHOGFD79L","branch_code":"PBVR","total_amt":325880,"product_details":[{"image":"1617382086515.jpg","cate":"Mobile Accessories"},{"image":"1617382322759.jpg","cate":"Mobile Accessories"},{"image":"CC251.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORIYDJLYSJ","branch_code":"MVPA","total_amt":1549500,"product_details":[{"image":"CC250.jpg","cate":"Mobile Accessories"},{"image":"CC256.jpg","cate":"Mobile Accessories"}]}];
const result = data.reduce((acc, {order_id, branch_code, product_details}) => {
acc[branch_code] ??= {[branch_code]: []};
acc[branch_code][branch_code].push({order_id, product_details});
return acc;
}, {});
console.log(Object.values(result));
let obj = {}
function comp(x) {
const f1 = data.filter(function (i) {
return i.branch_code === x
})
return f1
}
for (let i = 0; i < data.length; i++) {
obj[`${data[i].branch_code}`] = comp(data[i].branch_code)
}
console.log(obj)

How to map an array of Object in Javascript

I am stuck with mapping in array of objects.
Please find the below code
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => (x[city] = user));
});
Now it returns like this:
const resArray = [{ city1: "User1", city2: "User2", city3: "User2", city4: "User2" }]
I want the array like this:
const resArray = [
{ city1: ["User1"] },
{ city2: ["User1", "User2"] },
{ city3: ["User1", "User2"] },
{ city4: ["User2"] },
];
Can anyone please help me out.
Thanks
Try this
let x = {};
array.forEach((item) => {
item.cities.forEach((city) => {
x[city] = item.cities.includes(city) ? [...x[city] ? x[city] : [], item.user] : [];
});
});
You have been assigning user to city each time. Instead the x[city] should be an array and you should push the new user inside that array.
Try this,
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => {
if(x[city] && x[city].length) {
x[city].push(user);
} else{
x[city] = [user];
}
});
});
const res = Object.keys(x).map(key => { return {[key]: x[key]}});
console.log(res);

Json Array compare with different length in javascript

Below code which I am using for creating the new array if the id is the same in arr1 and arr2. But doesn't work since arr1 and arr2 are different. array 1 has index and arr2 is without index. screenshot for your reference. Can someone help?
Note: ID in arr1 is the same as EmpId in arr2
for(let i=0; i<arr1.length; i++) {
merged.push({
...arr1[i],
...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
);
}
console.log(merged);
Array1 looks like this :
[{"Active":1,"Id":1},
{"Active":1,"Id":3},
{"Active":1,"Id":2}]
Array2 looks something like this:
Below is the sample code on how I am framing array 2:
renderElement(activity){
var arr2 = [] ;
for(var i = 0; i < activity.length; i++) {
obj = activity[i];
if(obj.Id == 28){
fetch(geturl)
.then(function (response) {
return response.json();
})
.then(function (data) {
res = data;
arr2.push(res)
})
}
else{
// Do nothing
}
}
return arr2
}
Calling Render method like below:
outputarray = currentComponent.renderElement(activity);
console.log('output', outputarray)
Expected Output:
[{"Active":1,"Id":1,"Param1": true},
{"Active":1,"Id":3}, / Keep it as such if nothing exists in other array
{"Active":1,"Id":2, "Param2": false}]
You can try this approach instead:
Example #1
const arr1 = [
{ "Active":1, "Id":1 },
{ "Active":1, "Id":3 },
{ "Active":1, "Id":2 }
];
const arr2 = [
{
0: [
{
EmpId1: 1, Param1: true
}
]
},
{
1: [
{
EmpId2: 2,Param2: false
}
]
},
{
2: [
{
EmpId3: 2
}
]
},
];
const response = arr1
.reduce((acc, value) => {
const secondaryData = arr2.map((val, index) => {
const { [`EmpId${index + 1}`]: Id, ...others } = val[Object.keys(val)][0];
return { Id, ...others };
});
const match = secondaryData.findIndex(({ Id }) => Id === value.Id);
if (match >= 0) acc.push({...value, ...secondaryData[match]})
else acc.push(value);
return acc;
}, []);
console.log(response);
Example #2
const arr1 = [
{ "Active":1, "Id":1 },
{ "Active":1, "Id":3 },
{ "Active":1, "Id":2 }
];
const arr2 = [
[
{
EmpId1: 1,
Param1: true
}
],
[
{
EmpId2: 2,
Param2: false
}
],
[
{
EmpId3: 2
}
],
]
const response = arr1
.reduce((acc, value) => {
const secondaryData = arr2.map(([val], index) => {
const { [`EmpId${index + 1}`]: Id, ...others } = val;
return { Id, ...others };
});
const match = secondaryData.findIndex(({ Id }) => Id === value.Id);
if (match >= 0) acc.push({...value, ...secondaryData[match]})
else acc.push(value);
return acc;
}, []);
console.log(response);
Basically you can create a hash map by a object property and join on that property all the arrays, i.e. reduce an array of arrays into a result object, then convert the object's values back to an array. Since each array is reduced this means each array is only traversed once O(n) and the map object provides constant time O(1) lookup to match objects. This keeps the solution closer to O(n) rather than other solutions with a nested O(n) findIndex search, which yields a solution closer to O(n^2).
const mergeByField = (...arrays) => {
return Object.values(
arrays.reduce(
(result, { data, field }) => ({
...data.flat().reduce(
(obj, el) => ({
...obj,
[el[field]]: {
...obj[el[field]],
...el
}
}),
result
)
}),
{}
)
);
};
Load each array into a payload object that specifies the field key to match on. This will return all fields used to match by, but these can safely be ignored later, or removed, whatever you need. Example:
mergeByField(
{ data: arr1, field: "Id" },
{ data: arr2, field: "EmpId" },
);
const arr1 = [
{
Active: 1,
Id: 1
},
{
Active: 1,
Id: 2
},
{
Active: 1,
Id: 3
}
];
const arr2 = [[{ EmpId: 1, Param1: true }], [{ EmpId: 3, Param2: false }]];
const mergeByField = (...arrays) => {
return Object.values(
arrays.reduce(
(result, { data, field }) => ({
...data.flat().reduce(
(obj, el) => ({
...obj,
[el[field]]: {
...obj[el[field]],
...el
}
}),
result
)
}),
{}
)
);
};
console.log(
mergeByField({ data: arr1, field: "Id" }, { data: arr2, field: "EmpId" })
);

How can I add a unique ID to each object in an array?

I have this array of objects and I am trying to add a unique id to each object to have the desired output as shown below .But since I am new to Javascript this is a bit hard for me please can someone help me .
This is my Array Object Input:
const list = [
{"value": "Tape Measure"},
{"value": "Lawn Mower"}
],
]
This is my desired output with unique id's:
const desiredOuput = [
{
"id": "ur95tnnt949003",
"value": "Tape Measure",
},
{
"id": "0698080805kg",
"value": "Lawn Mower",
},
]
const list = [{
"data": [{
"value": "Tape Measure"
},
{
"value": "Lawn Mower"
}
],
"name": "Garden Todo",
}]
const res = list.map(o => {
o.data = o.data.map(d => ({ ...d,
id: randomId()
}));
return o;
})
console.log(res)
// Change this as desired
function randomId() {
return Math.random()
}
Here is sample method to generate randId.
In the method, 1) considering mix of numbers (0-9) and lower case alphabets (a-z). 2) required length of randId (size param)
const randId = (size) => {
const nums = Array.from({ length: 10 }, (_, i) =>
String.fromCharCode("0".charCodeAt(0) + i)
);
const alphabets = Array.from({ length: 26 }, (_, i) =>
String.fromCharCode("a".charCodeAt(0) + i)
);
const chars = [...nums, ...alphabets];
const rand = (length) => Math.floor(Math.random() * length);
return Array.from({ length: size }, () => chars[rand(chars.length)]).join("");
};
const list = [{ value: "Tape Measure" }, { value: "Lawn Mower" }];
const newlist = list.map(({ value }) => ({ value, id: randId(6) }));
console.log(newlist);
Try this...
const list = [{
"data": [{
"value": "Tape Measure"
},
{
"value": "Lawn Mower"
}
],
"name": "Garden Todo",
}]
const result = list.map(l => {
l.data = l.data.map(d => ({id:Math.floor(Math.random() * Date.now()), ...d}));
return l;
})
console.log(result);
This function will give you fully unique id
function genID() {
const timeStamp = Date.now();
let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
let Id = '';
for (let i = 0; i < 7; i++) {
let rom = Math.floor(1 +(str.length -1)*Math.random());
Id += str.charAt(rom);
}
Id += timeStamp.toString();
return Id;
}
You can also use only timeStamp
let id = Date.now();
npm install uuid
then:
const { v4: uuidv4 } = require('uuid');
list.forEach(el=> el.id = uuidv4());

Merge two json arrays

I have to array i want to merge them in one array by same id. So every two array have same id should be merged
Case 1:
{
"id":1212,
"instructor":"william",
...
}
Case 2:
[
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
I need the result to be :
{
"id": 1212,
"instructor": "william",
"Courses": [
{
"id":1212,
"name":"accounting",
...
},
{
"id":1212,
"name":"finance",
...
}
]
}
What you're asking isn't merging, but here is how you can do that.
const instructors = [{ "id":1212, "instructor":"william", }];
const courses = [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
];
const expected = [{ "id":1212, "instructor":"william", "courses": [
{ "id":1212, "name":"accounting" },
{ "id":1212, "name":"finance" }
]}];
const composed = instructors.map(ins => {
const ret = {...ins};
ret.courses = courses.filter(cou => cou.id === ins.id);
return ret;
});
console.log(composed);
var finArr;
var course = [];
use forEach loop javascript get all value in put your value instead of varid and varname
course.push({"id":varid,"name":varname});
finArr = {"id":variableId,"instructor":variablename,"Courses":course}

Categories