I got this input
var input=[ "Axel",
4,
4.21,
{ name : 'Bob', age : 16 },
{ type : 'fish', model : 'golden fish' },
[1,2,3],
"John",
{ name : 'Peter', height: 1.90} ];
and the Result must be this one
[ { name : 'Bob', age : 16 },
{ type : 'fish', model : 'golden fish' },
{ name : 'Peter', height: 1.90} ];
Using Array.prototype.filter, only keep Objects which are not Arrays
var input = ["Axel",
4,
4.21,
{name: 'Bob', age: 16},
{type: 'fish', model: 'golden fish'},
[1, 2, 3],
"John",
{name: 'Peter', height: 1.90}
];
input = input.filter(function (e) {
return (typeof e === 'object') && !Array.isArray(e);
}); /*
[
{"name": "Bob", "age": 16},
{"type": "fish", "model": "golden fish"},
{"name": "Peter", "height": 1.9}
]
*/
Try using array filter to remove the unwanted elements.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
To remove all integers
var filteredList = input.filter(function(val) {
return isNaN(val);
}):
/*
filteredList is now =
{ name: 'Bob', age: 16 },
{ type: 'fish', model: 'golden fish' },
[ 1, 2, 3 ],
'John',
{ name: 'Peter', height: 1.9 } ]
*/
Related
I have the data from the database and I want to push the duplicate value to each array. I attach the exact example I want.
// origin data
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
//result that I want to get
arr1 = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
];
arr2 = [
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
I want to create an array based on the name in this data and push it. Can anyone help?
One way would be to use reduce together with Object.values:
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
}
];
const result = Object.values(data.reduce((acc, cur) => {
const key = `${cur.name}:${cur.age}`;
const prev = acc[key] || [];
return {
...acc,
[key]: prev.concat(cur)
}
}, {}));
console.log(result);
How do I get 2 matching id between 2 array object using javascript?
// Array 1
const array1 = [
{id: 1, name: 'milla'},
{id: 2, name: 'alice'}
]
// Array 2
const array2 = [
{id: 3, name: 'bobba', height: '170cm', age: 22},
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
{id: 4, name: 'ricky', height: '168cm', age: 32},
]
the expected output is to returned array of object of Array2 that mached with id's on array1
// expected result
[
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
]
You could filter and look if the same id exists.
const
array1 = [{ id: 1, name: 'milla' }, { id: 2, name: 'alice' }],
array2 = [{ id: 3, name: 'bobba', height: '170cm', age: 22 }, { id: 2, name: 'alice', height: '169cm', age: 21 }, { id: 1, name: 'milla', height: '171cm', age: 24 }, { id: 4, name: 'ricky', height: '168cm', age: 32 }],
hash = array1.reduce((r, { id }) => (r[id] = true, r), {}),
filtered = array2.filter(({ id }) => hash[id]);
console.log(filtered);
The most efficient way to do this is to generate a map of the IDs in array1 and then filter array2 against those IDs, like so:
let array1 = [{ id: 1, name: 'milla' }, { id: 2, name: 'alice' }];
let array2 = [{ id: 3, name: 'bobba', height: '170cm', age: 22 }, { id: 2, name: 'alice', height: '169cm', age: 21 }, { id: 1, name: 'milla', height: '171cm', age: 24 }, { id: 4, name: 'ricky', height: '168cm', age: 32 }];
let idMap = array1.reduce((res, curr) => (res[curr.id] = true, res), {});
let filtered = array2.filter((item) => idMap[item.id]);
console.log(filtered)
Honestly, this is basic JS, but anyway, here's the solution:
const array1 = [
{id: 1, name: 'milla'},
{id: 2, name: 'alice'}
]
// Array 2
const array2 = [
{id: 3, name: 'bobba', height: '170cm', age: 22},
{id: 2, name: 'alice', height: '169cm', age: 21},
{id: 1, name: 'milla', height: '171cm', age: 24},
{id: 4, name: 'ricky', height: '168cm', age: 32},
]
const map = array1.reduce((a, c) => ({ ...a, [c.id]: true }), {});
const array3 = array2.filter(item => map[item.id]);
console.log(array3);
In React, I've got two state objects that hold multidimensional data like this:
this.state = {
itemList: [
{Id: 1, Name: "Bob", Age: 50},
{Id: 2, Name: "Fred", Age: 26},
{Id: 3, Name: "Joe", Age: 34},
],
newItemList: [],
}
I want to call a function to add an item from the first list to the second list, using the item's Id. For example:
addItem(1);
addItem(2);
//NEW VALUES:
itemList: [
{Id: 1, Name: "Bob", Age: 50},
{Id: 2, Name: "Fred", Age: 26},
{Id: 3, Name: "Joe", Age: 34},
],
newItemList: [
{Id: 1, Name: "Bob", Age: 50},
{Id: 2, Name: "Fred", Age: 26},
],
I then want to call a second function to search the second list, newItemList, to see if it contains an object by Id. If it does contain that Id, I want to remove the full object. Example:
checkItem(2);
function checkItem(item) {
if(isInNewList(item)) {
//Function checks for item 2 and removes item 2 from list
}
}
//NEW VALUE:
newItemList: [
{Id: 1, Name: "Bob", Age: 50},
],
I've done quite a bit of reading, but can't seem to grasp the concepts to make both of these happen easily. Both itemList and newItemList are stored in the current component's state. Thanks for any help!!
Use findIndex to check if the array contains the element, If it contains the element then use filter function to create a new array which does not include the object with the required id
let itemList = [{
Id: 1,
Name: "Bob",
Age: 50
},
{
Id: 2,
Name: "Fred",
Age: 26
},
{
Id: 3,
Name: "Joe",
Age: 34
},
]
let newItemList = [{
Id: 1,
Name: "Bob",
Age: 50
},
{
Id: 2,
Name: "Fred",
Age: 26
},
]
function searchByIndex(id) {
let getIndex = newItemList.findIndex(item => id === item.Id);
if (getIndex !== -1) {
newItemList = newItemList.filter(item => item.Id !== id)
}
}
searchByIndex(2);
console.log(newItemList)
I think a quite clean solution would be to do these operations with item IDs only
const itemIds = [
{Id: 1, Name: "Bob", Age: 50},
{Id: 2, Name: "Fred", Age: 26},
{Id: 3, Name: "Joe", Age: 34},
].map(item => item.id)
this.state = {
itemIds,
newItemIds: [],
}
const addItem = id => this.setState(
state => ({ newItemIds: state.newItemIds.concat(id) })
)
const removeIfPresent = idToRemove => this.setState({
state => ({ newItemsIds: state.newItems.filter(id => id !== idToRemove) })
)
Array1 = [ name1, name2];
Array2 = [ { name: name1 , id: 1, location: xyz, address: 123 },
{ name: name2 , id: 2, location: abc, address: 456 },
{ name: name3 , id: 3, location: def, address: 234 },
{ name: name4 , id: 4, location: ghi, address: 789 }
];
I have 2 arrays - Array1 and Array2. I want to filter Array2 by using Array1 such that my output comes as - [ { name: name1 , id: 1 }, { name: name2 , id: 2 }]. I tried like this - var ids = _.pluck(_.filter(Array2, a => _.contains(Array1, a.id)), 'id'); but problem with this is it's only giving one thing at a time means I can only get either name or id or location or address at a time but I want to filter name and id both at a time.
Loop over the second array and for each item look if the first contains it. If contains, includes will return true and that element will be in a new array.
Be aware this works only in ES6
var arr1 = [ 'A', 'B'];
var arr2 = [ { name: 'A' , id: 1,address: 123 },
{ name: 'B' , id: 2, address: 456 },
{ name: 'C' , id: 3, address: 234 },
{ name: 'D' , id: 4,address: 789 }
];
var newArr = arr2.filter(item => arr1.includes(item.name)).map(item => ({ name: item.name, id: item.id}));
console.log(newArr);
You could use a hash table for faster check if the wanted names are in the item for filtering.
var array1 = ['name1', 'name2'],
array2 = [{ name: 'name1', id: 1, location: 'xyz', address: 123 }, { name: 'name2', id: 2, location: 'abc', address: 456 }, { name: 'name3', id: 3, location: 'def', address: 234 }, { name: 'name4', id: 4, location: 'ghi', address: 789 }],
result = array2.filter(function (a) {
var hash = Object.create(null);
a.forEach(function (k) { hash[k] = true; });
return function (b) { return hash[b.name]; };
}(array1));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Instead of having to .filter and then .map it, just use .reduce.
Using reduce and includes, you can have something like this:
var Array1 = ["name1", "name2"];
var Array2 = [{
name: "name1",
id: 1,
location: "xyz",
address: 123
},
{
name: "name2",
id: 2,
location: "abc",
address: 456
},
{
name: "name3",
id: 3,
location: "def",
address: 234
},
{
name: "name4",
id: 4,
location: "ghi",
address: 789
}
];
var result = Array2.reduce((arr, cur) => {
if(Array1.includes(cur.name)) {
arr.push({
name: cur.name,
id: cur.id
})
}
return arr
}, [])
console.log(result)
Note, that you can use indexOf instead of includes if needing to support older browsers.
I have an array of objects as mentioned below,
var arraydata =[
{ id:1, name:"Abraham", age:20,gender:"male"},
{ id:2, name:"Annie", age:25,gender:"female"},
{ id:3, name:"Ryan", age:40,gender:"male"},
{ id:4, name:"Wayne", age:31,gender:"male"},
{ id:5, name:"Paul", age:45,gender:"male"}
];
how to convert this to a JSON data, which has only "id" and "name" field?
syntax is wrong age=20,gender="male" change it to age:20,gender:"male"
var arraydata =[
{ id:1, name:"Abraham", age: 20, gender:"male"},
{ id:2, name:"Annie", age: 25, gender:"female"},
{ id:3, name:"Ryan", age: 28, gender:"male"},
{ id:4, name:"Wayne", age: 19, gender:"male"},
{ id:5, name:"Paul", age: 45,gender:"male"}
];
var ans= arraydata.map(function(a){
return {id:a.id,name:a.name};
})
console.log(ans);
You can use the delete operator which remove a property from an object.
var arraydata = [{
id: 1,
name: "Abraham",
age : 20,
gender : "male"
}, {
id: 2,
name: "Annie",
age : 25,
gender : "female"
}, {
id: 3,
name: "Ryan",
age : 40,
gender : "male"
}, {
id: 4,
name: "Wayne",
age : 31,
gender : "male"
}, {
id: 5,
name: "Paul",
age : 45,
gender : "male"
}];
arraydata.forEach(function(item){ delete item.age; delete item.gender });
console.log(arraydata);
var arraydata =[
{ id:1, name:"Abraham", age: 20, gender: "male"},
{ id:2, name:"Annie", age: 25, gender: "female"},
{ id:3, name:"Ryan", age: 28, gender: "male"},
{ id:4, name:"Wayne", age: 19, gender: "male"},
{ id:5, name:"Paul", age: 45, gender: "male"}
];
var _ = arraydata.map(function(item) {
return { id: item.id, name: item.name };
});
var jsonData = JSON.stringify(_);
console.log(jsonData);
You can of course chain together the two steps.
Fiddle