Javascript arrays: How to remove the all matched elements which are contained in another array - arrays

I have 2 javascript arrays which are a, b and I want to remove the common elements from the array a.
Can you please help on this.
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];

It's basically a simple filter operation. I'd take the ids from b into an array, then filter by those elements
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];
const exists = b.map(e => e.id);
const res = a.filter(e => !exists.includes(e.id));
console.log(res);

Related

How do i map through array to get array of object?

I have an array called data. How do i extract sub_data? Just need the sub_data part for each object.
const data = [
{
id: 1,
title: 'Logo'
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands'
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
Example output will get two outputs because there is 2 objects:
const subData = [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
const subData = [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
Not very sure how to use the map function just to get sub_data in the correct structure
You can use flatMap to get sub_data in one array
const data = [
{
id: 1,
title: 'Logo',
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const result = data.flatMap(item => item.sub_data)
console.log(result)
If you want an array with the sub_data objects you can just map the original array:
const data = [
{
id: 1,
title: 'Logo',
'sub_data'
: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const mappedData = data.flatMap(obj => obj.sub_data)
console.log(mappedData)
Another solution would be to use the .forEach function of javascript.
const subData = [];
data.forEach(item => subData.push(...item.sub_data))

Access Array from Property in Nested Object

I have the following nested object:
export const mockData = {
sections: [
{
name: 'Client',
subSections: [
{
name: 'Client Detail'
}
]
},
{
name: 'Sales',
subSections: [
{
name: 'Overview',
subSections: [
{
name: 'Overview - A',
fields: [
{
key: 'firmName',
type: 'input',
templateOptions: {
label: 'Firm Name',
required: true
}
},
{
key: 'requestOption',
type: 'select',
templateOptions: {
label: 'Request Option',
required: true,
options: [
{ value: '1', label: '1' },
{ value: '2', label: '2' },
{ value: '3', label: '3' },
{ value: '4', label: '4' }
]
}
},
{
key: 'region',
type: 'select',
templateOptions: {
label: 'Region',
required: true,
options: [
{ value: '1', label: '1' },
{ value: '2', label: '2' },
{ value: '3', label: '3' },
{ value: '4', label: '4' },
{ value: '5', label: '5' }
]
}
}
]
}
]
}
]
}
]
};
and I would like to access the array from the fields property in order to render a form. Right now what I have is overviewA: FormlyFieldConfig[] = mockData.sections[1].subSections[0].subSections[0].fields, but I am facing the error of
Property 'subSections' does not exist on type '{ name: string; }'.
However, this error goes away when do a work-around and I add the property subSections to the nested object like so:
export const mockData = {
sections: [
{
name: 'Client',
subSections: [
{
name: 'Client Detail',
subSections: []
}
]
},
{
name: 'Sales',
subSections: [
{
name: 'Overview',
subSections: [
{
name: 'Overview - A', ...
I was wondering why
I was facing the issue without the work-around, and
How can I access the array from the property fields without the work-around?

Get 100% with rounded percentages of objects values in an array

I have an array of objects, and a value of the objects is a percent. Is there a way to round those values and still get 100% if added?
const items = [
{
name: 'Something',
value: 20.4
},
{
name: 'something else',
value: 36.6
},
{
name: 'another thing',
value: 21.5
},
{
name: 'other item',
value: 21.5
}
];
and return something like this
const items = [
{
name: 'Something',
value: 20
},
{
name: 'something else',
value: 37
},
{
name: 'another thing',
value: 21
},
{
name: 'other item',
value: 22
}
];
One way to achieve this is to iterate over the array, maintaining a rolling sum of the rounded values and then setting the last value in the array to 100 - sum:
const items = [
{ name: 'Something', value: 20.4 },
{ name: 'something else', value: 36.6 },
{ name: 'another thing', value: 21.5 },
{ name: 'other item', value: 21.5 }
];
let sum = 0;
const rounded = items.map(({name, value}, i) => {
if (i == items.length - 1) {
return { name, value: 100 - sum };
}
value = Math.round(value);
sum = sum + value;
return { name, value };
});
console.log(rounded);

How to fetch Json nested and Make it Array of object in React

I'm setting up an array of list, and want to parse the value from JSON to that list
This is the array
const universityOptions = [
{ key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
{ key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
{ key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
{ key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
{ key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
{ key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]
Below is the json
{"success":true,"data":[{"id":1,"name":"University 1"},{"id":2,"name":"University 2"},{"id":3,"name":"University 3"},{"id":4,"name":"University 4"},{"id":5,"name":"University 5"},{"id":6,"name":"University 6"}]}
and this is the method i tried so far, which i get the data but i only need the data.name (university name) and i'm stuck how to get it
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
this.setState({
university_list: univJson.data
})
console.log(univJson.data);
})
}
Result
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: "University 1"}
1: {id: 2, name: "University 2"}
2: {id: 3, name: "University 3"}
3: {id: 4, name: "University 4"}
4: {id: 5, name: "University 5"}
5: {id: 6, name: "University 6"}
length: 6
__proto__: Array(0)
I expect the output is an array like
const universityOptions = [
{ key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
{ key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
{ key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
{ key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
{ key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
{ key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]
Thanks
Try it like this:
const newArray = json.data.map(elem => ({
key: elem.id.toString(),
text: elem.name,
value: elem.name
}));
Your componentDidMount() would end up being something like this:
componentDidMount() {
const univFetch = fetch('url')
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
const universityList = univJson.data.map(elem => ({
key: elem.id.toString(),
text: elem.name,
value: elem.name
}));
this.setState({
university_list: universityList
})
})
}
Here's the Sandbox if you want to take a look at it. Hope it helps.
You need to iterate over your response and you can create desired output like this,
this.setState({
university_list : univJson.data.map(data => ({key:data.id,text:data.name,value:data.name}))
}, ()=>console.log(this.state.university_list))
Error is use forEach on univJson and create an array
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
let univArray = [];
univJson.forEach((datum, index) => {
univArray.push({ key: datum.id, text: datum.name, value: datum.name});
})
this.setState({
university_list: univArray
})
console.log(univJson.data);
})
}
Why not perform an extra operation,
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
var output = [];
for(var i=0 ;i<univJson.data;i++){
var obj = {key : univJson.data[i]["id"],
text : univJson.data[i]["name"],
value : univJson.data[i]["name"]
}
output.push(obj)
}
this.setState({
university_list: output
});
console.log(output);
})
}

ng-change blanking out dropdown

I have this drop down setup like this:
<div class="col-sm-2">
<select class="form-control" name="dataType" id="dataType"
ng-model="dataTypes"
ng-change="typeCheck()">
<option ng-repeat="option in dataTypes" value="{{option.id}}">{{option.name}}</option>
</select>
</div>
In my controller I have this function:
$scope.typeCheck = function () {
alert($scope.dataTypes);
};
After this function is called, sometimes my list disappears! I say sometimes as because it is only on certain elements that get called.
This is my array that gets loaded into the dropdown:
$scope.typeArrays = function () {
var vm = this;
vm.dataTypes = [];
vm.dataTypes = [
{ id: 'bigint', name: 'bigint' },
{ id: 'binary', name: 'binary' },
{ id: 'bit', name: 'bit' },
{ id: 'char', name: 'char' },
{ id: 'date', name: 'date' },
{ id: 'datetime', name: 'datetime' },
{ id: 'datetime2', name: 'datetime2' },
{ id: 'datetimeoffset', name: 'datetimeoffset' },
{ id: 'decimal', name: 'decimal' },
{ id: 'float', name: 'float' },
{ id: 'image', name: 'image' },
{ id: 'int', name: 'int' },
{ id: 'money', name: 'money' },
{ id: 'nchar', name: 'nchar' },
{ id: 'ntext', name: 'ntext' },
{ id: 'numeric', name: 'numeric' },
{ id: 'nvarchar', name: 'nvarchar' },
{ id: 'real', name: 'real' },
{ id: 'smalldatetime', name: 'smalldatetime' },
{ id: 'datetimeoffset', name: 'datetimeoffset' },
{ id: 'smallint', name: 'smallint' },
{ id: 'smallmoney', name: 'smallmoney' },
{ id: 'sql_variant', name: 'sql_variant' },
{ id: 'text', name: 'text' },
{ id: 'time', name: 'time' },
{ id: 'tinyint', name: 'tinyint' },
{ id: 'uniqueidentifier', name: 'uniqueidentifier' },
{ id: 'varbinary', name: 'varbinary' },
{ id: 'varchar', name: 'varchar' }
];
}
Here is a fiddle of my code.
You were pretty close, there was a little misconception about the models but this way, you set a dataType using ng-model and ng-change alerts the chosen dataType.
$scope.dataType = null;
$scope.dataTypes = [
{ id: 'bigint', name: 'bigint' },
{ id: 'binary', name: 'binary' },
{ id: 'bit', name: 'bit' },
{ id: 'char', name: 'char' },
{ id: 'date', name: 'date' },
{ id: 'datetime', name: 'datetime' },
{ id: 'datetime2', name: 'datetime2' },
{ id: 'datetimeoffset', name: 'datetimeoffset' },
{ id: 'decimal', name: 'decimal' },
{ id: 'float', name: 'float' },
{ id: 'image', name: 'image' },
{ id: 'int', name: 'int' },
{ id: 'money', name: 'money' },
{ id: 'nchar', name: 'nchar' },
{ id: 'ntext', name: 'ntext' },
{ id: 'numeric', name: 'numeric' },
{ id: 'nvarchar', name: 'nvarchar' },
{ id: 'real', name: 'real' },
{ id: 'smalldatetime', name: 'smalldatetime' },
{ id: 'datetimeoffset', name: 'datetimeoffset' },
{ id: 'smallint', name: 'smallint' },
{ id: 'smallmoney', name: 'smallmoney' },
{ id: 'sql_variant', name: 'sql_variant' },
{ id: 'text', name: 'text' },
{ id: 'time', name: 'time' },
{ id: 'tinyint', name: 'tinyint' },
{ id: 'uniqueidentifier', name: 'uniqueidentifier' },
{ id: 'varbinary', name: 'varbinary' },
{ id: 'varchar', name: 'varchar' }
];
$scope.colOptions= [];
$scope.colOptions= [
{ id: '1', name: 'identity(1,1)' },
{ id: '2', name: 'constraint' }
];
$scope.typeCheck = function () {
alert($scope.dataType);
};
fiddle https://jsfiddle.net/5extmuqg/
#webdad3, cool. thanks for the fiddle.
This can be fixed with a couple of small changes. vm.datatypes (in your function) should become $scope.dataTypes. ANd the ng-model in your select should be dataType, NOT dataTypes. Lastly, in typeCheck(), also refer to $scope.dataType (singular).
the vm. notation is usually used when you want to use controller-as syntax rather than $scope. Since you're using $scope, just stick with that. And the ng-model for the <select> element should be the object you want to set, not the object providing the list of options.
Working Fiddle
Hope this helps

Resources