I want to get an array with filtered values.
My arrays are like,
let arr=[{name:'trt,tet', id:5},{name:td, id:25},{name:fxg, id:1},{name:fs, id:4},{name:ste, id:41}]
&
let arr1 =[{data:fxg, addr:po 87987},{data:tert, addr:po8798fvd7},{data:trt, addr:po 887},{data:trhd, addr:po 8798787}]
my resultant array that I want is,
let rslt =[data:tert, addr:po8798fvd7},{data:trhd, addr:po 8798787}]
that is in arr the object 'name' which is also in arr1 with name 'data' I don't need that array. nd some of which contain more than one name. I want to filter it.
try this
let arr=[{name:'trt,tet', id:5},{name:'td', id:25},{name:'fxg', id:1},{name:'fs', id:4},{name:'ste', id:41}]
let arr1 =[{data:'fxg', addr:'po 87987'},{data:'tert', addr:'po8798fvd7'},{data:'trt', addr:'po 887'},{data:'trhd', addr:'po 8798787'}]
const names = arr.flatMap(a => a.name.split(','))
const res = arr1.filter(a => !names.includes(a.data))
console.log(res)
This uses a Set which is optimized for lookups in O(1) and therefore the runtime of the algorithm is O(n) in contrast to using includes() which will result in a runtime of O(n²).
let arr = [
{ name: "trt", id: 5 },
{ name: "td", id: 25 },
{ name: "fxg", id: 1 },
{ name: "fs", id: 4 },
{ name: "ste", id: 41 },
];
let arr1 = [
{ data: "fxg", addr: "po87987" },
{ data: "tert", addr: "po8798fvd7" },
{ data: "trt", addr: "po887" },
{ data: "trhd", addr: "po8798787" },
];
// use array for quick lookups in O(1)
const set = new Set(arr.map(item => item.name));
// filter arr1 adding only items to result that are not in Set
const result = arr1.filter(item => !set.has(item.data))
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I want to store the array values in an object like below:
{"newpublicareas":[{"area_name":"x",
"level":0}]}
This is what i have done:
getNewTopLevelS(res){
this.newpublicarea = []
res.map((j)=> {
this.newpublicarea.push(j.body.data.areas)
})
this.entireareas.push(this.newpublicarea)
}
But it is pushing in wrong format.
Any suggestions?
Check this,
var res = [{"area_name":"x","level":0},{"area_name":"y","level":4},]
var newpublicarea = {newpublicarea:[]}
res.map((j)=> {
newpublicarea.newpublicarea.push(j)
})
console.log(newpublicarea)
Gives
{
newpublicarea: [{
area_name: "x",
level: 0
}, {
area_name: "y",
level: 4
}]
}
https://jsfiddle.net/1ev6tq4w/
I have the following code, which basically adds empty objects to an array.
handleAddNewRow = () => {
this.setState({
rowData: [
{ MEMBER: "", ALIAS: "", STATUS: "" },
...this.state.rowData
]
})
}
Lets say, I am passing an integer value to the function handleAddNewRow and then it dynamically adds the number of empty objects to the array based on the integer value, How is it possible?
You can look at my function:
handleAddNewRow = (number) => {
this.setState({
rowData: [
...this.state.rowData,
...(new Array(number).fill({ MEMBER: "", ALIAS: "", STATUS: "" }))
]
});
}
in the following code i wrote code in simple condition
change it on your own
const array = [{name: '', family: ''}]
function a(num, arr) {
let temp = [...arr, {name: '', family: ''}]
if (num - 1 > 0) {
temp = a(num - 1, temp)
}
return temp
}
const b = a(4, array)
console.log(b)
I am currently struggling with this problem. Hopefully, you can help me :)
Data is selected from a Database and it returns Objects structured like this:
object = {
id: 4,
name: "Banana",
idParent: 1
}
idParent would be the section of the product.
There are a lot of products and a lot of sections so a simple
const sectionOne = [];
ObjectList.map(e => {
if(e.idParent === 1) {
sectionOne.push(e);
}
})
would probably be wrong, because it should be possible to add other idParents in the future and code should not need some rework in that case.
Let's say there are 30 Objects, 10 have idParent = 1, 15 have idParent = 2 and the last 5 have idParent = 3.
How can the whole list be divided into these sections without making a variable for each section?
Thanks for the help :)
What I believe you need here is a map which groups the values of the list by idParent.
Example:
const objectList = [{
id: 4,
name: "Banana",
idParent: 1
},
{
id: 3,
name: "apple",
idParent: 2
},
{
id: 5,
name: "orange",
idParent: 2
}];
const groupBy = (array, key) => {
return array.reduce((accumlator, value) => {
(accumlator[value[key]] = accumlator[value[key]] || []).push(value);
return accumlator;
}, new Map());
};
const resultMap = groupBy(objectList, "idParent");
console.log(resultMap);
enter code here
The sub-arrays from the map can be access also like this:
const groupWihtIdParen1 = resultMap[1];
// or like this
const groupWithIdParent2 = resultMap.get(2);
``
I have an array of objects
var myArray = [
{id: 1, name: 'Foo Bar', email: 'foo#bar.com'},
{id: 2, name: 'Bar Foo', email: 'bar#foo.com'},
{id: 3, name: 'Joe Ocean', email: 'joe#ocean.com'},
{id: 3, name: 'Jenny Block', email: 'foo#bar.com'},
];
I am expecting the following output:
commonIdsObjects = [
{id: 3, name: 'Joe Ocean', email: 'joe#ocean.com'},
{id: 3, name: 'Jenny Block', email: 'foo#bar.com'},
]
I assume that you want the output to be a single array containing all the duplicate entries, even if some of those entries have different ids. For example, if you had added {id: 2, name: 'Fishy Joe', email: 'com#foo.bar'} to myArray, the resulting commonIdsObjects would be an array of four items: two for id: 2 and two for id: 3. If this is not what you want then you should take care to specify exactly the expected behavior.
Anyway, assuming you have a type corresponding to the elements of myArray, like this:
type Elem = typeof myArray[number];
And assuming your target runtime has access to the Object.values() and Array.prototype.flat() methods, then you can write
const commonIdsObjects = Object.values(
myArray.reduce<{ [k: number]: Elem[] }>(
(a, v) => ((a[v.id] || (a[v.id] = [])).push(v), a), {}
)
).filter(c => c.length > 1).flat(1);
What we're doing is using myArray.reduce() to build an object whose keys correspond to your elements' id values, and whose values are arrays of elements with those id. We convert this object into an array of arrays of elements, keep only those whose lengths are more than one (i.e., any id with more than one element corresponding to it), and flatten into a single array.
This will produce the desired result:
console.log(JSON.stringify(commonIdsObjects));
// [{"id":3,"name":"Joe Ocean","email":"joe#ocean.com"},
// {"id":3,"name":"Jenny Block","email":"foo#bar.com"}]
If you don't have access to Object.values() and [].flat() you can use Object.keys() and [].reduce() instead:
type ElemsById = { [k: string]: Elem[] }
const commonIdsObjects2 = ((o: ElemsById) => Object.keys(o).map(k => o[k]))(
myArray.reduce<ElemsById>(
(a, v) => ((a[v.id] || (a[v.id] = [])).push(v), a), {}))
.filter(c => c.length > 1).reduce<Elem[]>((a, v) => (a.push(...v), a), []);
console.log(JSON.stringify(commonIdsObjects2)); // same
which is essentially the same algorithm. Or you could do this algorithm the purely-imperative-programming way with various for loops:
const elemsById: ElemsById = {};
for (let v of myArray) {
if (!elemsById[v.id]) {
elemsById[v.id] = []
}
elemsById[v.id].push(v);
}
const commonIdsObjects3: Elem[] = []
for (let k in elemsById) {
if (elemsById[k].length <= 1) {
continue;
}
for (let v of elemsById[k]) {
commonIdsObjects3.push(v);
}
}
console.log(JSON.stringify(commonIdsObjects3)); // same
Okay, hope that helps; good luck!
Playground link to code
var myArray = [
{ id: 1, name: "Foo Bar", email: "foo#bar.com" },
{ id: 2, name: "Bar Foo", email: "bar#foo.com" },
{ id: 3, name: "Joe Ocean", email: "joe#ocean.com" },
{ id: 3, name: "Jenny Block", email: "foo#bar.com" }];
const commonIdsObjects = myArray.filter(x => x.id === 3);
console.log(commonIdsObjects);
I have an array of objects. I want to find the max value and the one before that.
arr : [{key:1, value: 1},{key:2, value: 2}, {key:3, value: 3}, {key:4, value: 4}, {key:5, value: 5}]
let largest = 0;
greater = 0;
val = [];
this.arr.forEach(aa => {
if (largest < Number(aa.value)) {
largest = Number(aa.value);
greater = aa.key;
}
});
}
The value of greater is 5; I want to get the value 4 too and push both of them to val array.
The best way to achieve the same is by using the Array prototype function sort().
What you need to do is sort in descending order and grab the first two elements.
MDN link for sort() documentation
Here's how I would write it.
let newArr = arr.sort(function(a, b){
return b.value-a.value;
});
Now you can grab the top two values in newArr.
Separate values of the array. Get the maximum value using Math.max, then filter your array and get another one which does not contain the max1 value from the first search and do the same on the filtered array.
const arr = [
{ key: 1, value: 1 },
{ key: 2, value: 2 },
{ key: 3, value: 3 },
{ key: 4, value: 4 },
{ key: 5, value: 5 }
];
const valuesMax1 = arr.map(item => item.value);
const max1 = Math.max(...valuesMax1);
const valuesMax2 = valuesMax1.filter(item => item !== max1);
const max2 = Math.max(...valuesMax2);
console.log(max1);
console.log(max2);
Another simple way is to sort array and get first two items
const arr = [
{ key: 1, value: 1 },
{ key: 2, value: 2 },
{ key: 3, value: 3 },
{ key: 4, value: 4 },
{ key: 5, value: 5 }
];
const sorted = arr.sort((f,s) => s.value - f.value);
console.log(sorted[0].value);
console.log(sorted[1].value);