How to join/add strings in an array object - javascript

I've an array which has objects inside it:
[
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
I would like to join all the strings i.e pointName like this : "One-Two-Three"
Any help is appreciated. Thanks.
Edit 1:
This is what I tried so Far:
this.viaPoints.forEach(x=> {
var splitted = x.pointName.split(" ");
console.log('I5: ',splitted[0].join("-"));
});
The reason I've split is because the string will have extra characters some times like "One - A". So I've used split to remove the extra
Edit 2:
In my case this helped as I mentioned above that to remove extra characters and strings:
var permittedValues1 = this.viaPoints.map(value => value.pointName.split(" ")[0]).join("-") ;

You can use .map and .join functionalities too. Here .map will take the values based upon the key-pointName and .join is used to return an array as a string. The elements will be separated by a specified separator (here "-").
let array = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
];
var permittedValues = array.map(value => value.pointName).join("-") ;

You can use Array.prototype.reduce function to return an array which contains pointName for each object in the array and join all value of the return array with -.
let data = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
let result = data.reduce((accumulator, current) => {
return accumulator.concat(current.pointName);
}, []).join('-');
console.log(result);

Related

Merging elements in my SQL query result Array with Javascript [duplicate]

This question already has answers here:
Group by array and add field and sub array in main array
(8 answers)
Closed 1 year ago.
As a newbie, I'm looking for the best approach to achieve the below:
Here is the Array I get from my DB query that contains a left join on the "class" table
[
{"legnumber":1,
"classcode" : "J"},
{"legnumber":1,
"classcode" : "Y"},
{"legnumber":2,
"classcode" : "J"}
]
And I would like to get something like this:
{
"legs": [
{
"legnumber" : 1,
"classes" : [
{"classcode" : "J"},
{"classcode" : "Y"}
]
},
{
"legnumber" : 2,
"classes" : [
{"classcode" : "J"}
]
}
]
}
Thanks a lot for your suggestions.
I'm using Sequelize in this project but I'm writing raw queries as I find it more convenient for my DB model.
Regards,
Nico
Hassan's answer is the more concise way to handle this, but here is a more verbose option to help understand what's happening:
const queryResults = [
{ legnumber: 1, classcode: 'J' },
{ legnumber: 1, classcode: 'Y' },
{ legnumber: 2, classcode: 'J' },
]
// create an object to store the transformed results
const transformedResults = {
legs: [],
}
// loop through each item in the queryResult array
for (const result of queryResults) {
// try to find an existing leg tha matches the current leg number
let leg = transformedResults.legs.find((leg) => leg.legnumber === result.legnumber)
// if it doesn't exist then create it and add it to the transformed results
if (!leg) {
leg = {
legnumber: result.legnumber,
classes: [],
}
transformedResults.legs.push(leg)
}
// push the classcode
leg.classes.push({ classcode: result.classcode })
}
console.log(transformedResults)
You can group your array items based on legnumber using array#reduce and then get all the values to create your result using Object.values().
const arr = [ {"legnumber":1, "classcode" : "J"}, {"legnumber":1, "classcode" : "Y"}, {"legnumber":2, "classcode" : "J"} ],
output = arr.reduce((r, {legnumber, classcode}) => {
r[legnumber] ??= {legnumber, classes: []};
r[legnumber].classes.push({classcode});
return r;
},{}),
result = {legs: Object.values(output)};
console.log(result);

Find the difference between two arrays based on some the value inside a nested array

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

JavaScript - Filtering an array of strings

I have an array of arrays of data returning to me back from a csv file. I am attempting to filter out each index of an array depending on which title is in the array. For example:
If an index of the array has the name "Retail" return that entire index which includes some values.
Here is my array :
[
​​[
"Retail",
​​
"22,477",
​​
"24,549",
​​
"19,580",
​​
"15,358",
​​], ​ ​
[
"Online",
"8,653",
"7,586",
"2,432",
"4,321"
],
[
"In Store",
"2,532",
"2,836",
"5,632",
"7,325"
]
]
I've attempted these two separate ways and both are returning an array of 0:
filtArr = dataList.filter(name => name.includes('Retail')) //expecting the array length 5 with "Retail" and it's values
attempt 2
filtArr = dataList.filter(function (name) {
return (name === "Retail")
})
Expected return is: console.log(filtArr) // [ 0. "Retail", 1. "22,477", 2. "24,549", 3. "19,580", 4. "15,358"
A good way to check if an array contains some item is to test it with the indexOf method.
It will return -1 if the item is not found or else its index.
You could do this to store all arrays containing 'Retail' in them:
let retailArrays = [];
arrayOfArrays.forEach(
array => {
if( array.indexOf('Retail') !== -1) {
retailArrays.push(array);
};
}
)
You apparently have trailing spaces after some of the names, so maybe "Retail" is actually "Retail ".
It also looks like the name is always the first element of the nested array, so there's no need to search the whole array.
So use trim() on the first element to remove the surrounding spaces.
filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');
var dataList = [
[
"Retail",
"22,477",
"24,549",
"19,580",
"15,358",
],
[
"Online",
"8,653",
"7,586",
"2,432",
"4,321"
],
[
"In Store",
"2,532",
"2,836",
"5,632",
"7,325"
]
];
filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');
console.log(filtArr);

Assign values of object on another array in JavaScript

I have an array of objects and an array of primitive values. I want to create a new array of objects that maps the values of the first to the latter.
Here's the array of objects:
var eventInstances = [
{
id: 1,
title: "Item 1"
},
{
id: 2,
title: "Item 2"
},
{
id: 1,
title: "Item 3"
},
{
id: 3,
title: "Item 4"
},
]
And the array of primitive values:
var dates = [1, 2, 3]
I want map the objects of eventInstances to a new Array of objects with the values of dateInstances as keys, which would correspond with the value of id in eventInstances.
The result should be:
var dateInstances = [
{
id: 1,
instances: [
{
title: "Item 1"
},
{
title: "Item 1"
}
]
},
{
id: 2,
instances: [
{
title: "Item 1"
},
{
title: "Item 1"
}
]
},
{
id: 3,
instances: [
{
title: "Item 2"
}
]
}
];
Sorry, if this is a newbie question, I've been reading up on sorting methods, but I'm quite at a loss here. Any hint would be highly appreciated. Thanks!
This function will give you your expected result.
dates.map(id=>{
return {id:id,
instances:eventInstances.filter(item =>{
return item.id === id;
})
.map(foundItem => {
return {title: foundItem.title}
})
}});
Might be a simpler way to do it, but here's what's happening. Use map to iterate through your dates array. Then filter to find items in eventInstances that match, then map through those again to just return the title.
Array.map docs
Array.filter docs
You actually don't need the second array, as all those id can be found in the data.
You could collect the data in a map keyed by id and then extract the values:
const eventInstances = [{id: 1,title: "Item 1"},{id: 2,title: "Item 2"},{id: 1,title: "Item 3"},{id: 3,title: "Item 4"}];
const map = new Map(eventInstances.map(({id}) => [id, {id, instances: []}]));
eventInstances.forEach(({id, title}) => map.get(id).instances.push({ title }));
const result = [...map.values()];
console.log(result);
This creates a Map from the data. The Map is populated using its constructor argument, which can accept an array of pairs as input. Such a pair will serve as key/value pair in the Map being constructed. The pairs that are given to the constructor look like this:
[id, {id, instances: []}]
And so the Map will have its keys set to ids and its values will be objects in the form {id, instances: []}. Duplicate id values will not result in extra entries... they will be ignored in the process.
The next step is the forEach loop, which puts values inside those instances properties.
Finally, the keys of the Map have served their purpose, they can now be ejected. We only need the values, which are turned into an array through the spread syntax.
I think you are looking for an object where the key equals to the id, and the value equals to an array of titles, like:
{
"0":[
"title1",
"title2"
],
"1":[
"title1",
"title2"
],
}
To achieve that you need:
var dateInstances = {};
for(let i =0; i<eventInstances.length;i++){
if (!Array.isArray(dateInstances[eventInstances[i]["id"]])){
dateInstances[eventInstances[i]["id"]] = [];
}
dateInstances[eventInstances[i]["id"]].push(eventInstances[i]["id"]["title"]);
}

Javascript: How to insert a row at an index to a multidimensional array?

I am novice programmer in javascript. Kindly guide me in the right path.
Below is a 3D array of size 2 x 3 x 3
"items": [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ]
Now, I need to insert a row, something like [ [19,20,21], [22,23,24], [25,26,27] ] at an index 1 or 2.
I tried with splice function, but all in vain.
Being a multi dimensional array, I don't know what value goes into the itemN parameter of the splice function.
items.splice(insertIndex, 0, `????`);
How can I accomplish it? Thanks
use splice with deleteCount 0 (second parameter). as thrid param you enter the 2-dimensional array you want to add.
var items = [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ];
var add = [ [19,20,21], [22,23,24], [25,26,27] ];
items.splice(insertIndex, 0, add);
working example here: jsfiddle
You can pass complete array which you want to insert to splice parameter, like:
items.splice(2, 0,[ [19,20,21], [22,23,24], [25,26,27] ]);
DEMO
The accepted answer is good.
I make an demo to insert middle row in angular as reference.
I share for whom concerned.
textarray = [
[{ text: "Content 1" }, { text: "Content 2" }],
[{ text: "Content 3" }, { text: "Content 4" }]
];
rowindex = 1;
insertmiddle() {
let size = this.textarray[0].length;
this.textarray.splice(this.rowindex, 0,
Array(size).fill({ text: "Content", tag: "Content" }));
}
https://stackblitz.com/edit/angular-insert-row-matrix

Categories