adding a key to an array of objects in javascript - javascript

I am trying to add the key 'greeting' to an array of objects. My code is adding the key as expected but the only problem is that, it is adding another array at the bottom when I console log.
function greetDevelopers(list) {
list.greeting = list.map(x => x.greeting = `Hi ${x.firstName}, what do
you like most about ${x.language}?` );
console.log(list);
};
It is returning the following
[ { firstName: 'Sofia',
lastName: 'I.',
country: 'Argentina',
continent: 'Americas',
age: 35,
language: 'Java',
greeting: 'Hi Sofia, what do you like most about Java?' },
{ firstName: 'Lukas',
lastName: 'X.',
country: 'Croatia',
continent: 'Europe',
age: 35,
language: 'Python',
greeting: 'Hi Lukas, what do you like most about Python?' },
{ firstName: 'Madison',
lastName: 'U.',
country: 'United States',
continent: 'Americas',
age: 32,
language: 'Ruby',
greeting: 'Hi Madison, what do you like most about Ruby?' },
greeting: [ 'Hi Sofia, what do you like most about Java?',
'Hi Lukas, what do you like most about Python?',
'Hi Madison, what do you like most about Ruby?' ] ]
Any suggestions on how to keep the greeting in each object but remove it from the end. would be greatly appreciated.
Thanks

You shouldn't be assigning to list.greeting - that assigns the result to the array (the new property that you see at the end of the array - arrays shouldn't have properties like that, only elements). What you want is just side-effects (not a new array), so you should use forEach instead of map (and don't assign the result to anything - simply log the array again):
const input = [ { firstName: 'Sofia',
lastName: 'I.',
country: 'Argentina',
continent: 'Americas',
age: 35,
language: 'Java',
}, { firstName: 'Lukas',
lastName: 'X.',
country: 'Croatia',
continent: 'Europe',
age: 35,
language: 'Python',},
{ firstName: 'Madison',
lastName: 'U.',
country: 'United States',
continent: 'Americas',
age: 32,
language: 'Ruby',
}];
function greetDevelopers(list) {
list.forEach((item) => {
item.greeting = `Hi ${item.firstName}, what do you like most about ${item.language}?`;
});
console.log(list);
}
greetDevelopers(input);

You need to update each object of the array and return a new array.In this list.greeting it is just creating a new key instead of the creating greeting key in each object.
let orgArray = [{
firstName: 'Sofia',
lastName: 'I.',
country: 'Argentina',
continent: 'Americas',
age: 35,
language: 'Java'
}, {
firstName: 'Lukas',
lastName: 'X.',
country: 'Croatia',
continent: 'Europe',
age: 35,
language: 'Python'
}, {
firstName: 'Madison',
lastName: 'U.',
country: 'United States',
continent: 'Americas',
age: 32,
language: 'Ruby'
}]
function greetDevelopers(list) {
let newArr = list.map(function(x) {
x.greeting = `Hi ${x.firstName}, what do you like most about ${x.language}?`
return x;
})
return newArr;
};
console.log(greetDevelopers(orgArray))

Related

How to find index at similar items during the comparing of two arrays with object in JS

I have 2 arrays with objects.
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
],
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
],
I need to get index from users1 of that parts that are contains in users2.
As a result I should get [{1: true}, {3: true}].
I try in this way but it's not correct
const arr = user1.filter((item, index) => user2.map(i) => {
if(i.id === item.id) return {index: true}
return null;
})
You could create a Set of all ids from users2 (a Set is somewhat like an array, but allows you to quickly check if a value is in it using .has() and it only stores unique values). Once you have the set, you can use .reduce() to create a new array, where you can use .concat() if the set has the id of the object from users1:
const users1 = [{ id: 1, name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' }, { id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 3, name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const users2 = [{ id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const u2Ids = new Set(users2.map(user => user.id));
const res = users1.reduce((acc, obj, i) => u2Ids.has(obj.id) ? acc.concat({[i]: true}) : acc, []);
console.log(res);
When creating your objects you need to ensure you use computed property names when adding the index as a key {[i]: true} so that the value at i is used rather than the literal i name. The above can also be written with a for..of loop (by accessing Array.prototype.entries()), which is more efficient and (in my opinion) more readable:
const users1 = [{ id: 1, name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' }, { id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 3, name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const users2 = [{ id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const res = [];
const u2Ids = new Set(users2.map(user => user.id));
for(const [i, obj] of users1.entries()) {
if(u2Ids.has(obj.id))
res.push({[i]: true});
}
console.log(res);
First your array don't contains ids I filtered name for now.Also filter will not work here bcs if you use filter that will just filter your array and index will no longer be the same try following instead
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }
];
const arr = [];
users1.forEach((item, idx) =>{
if(users2.some(u=> u.name == item.name)){
arr.push({[idx]:true})
}
});
console.log(arr)
Just another approach - with Array.reduce()
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const arr = users1.
reduce((previousValue, currentValue, index) => {
// change here to find by id
if (users2.some(u2 => u2.name === currentValue.name) ){
// map to whatever you want
const valueToSave = {[index] : true};
return [...previousValue, valueToSave];
} else {
return previousValue;
}
}, []);
console.log(arr);
#festina, to keep it simple we map on users2, as we are trying to find objects of users1 in users2, we get index using findIndex using (id/name any unique key available) and then filter by index > 0, and format the result in required format
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
// your solution
const result = users2.map((user, index) => users1.findIndex(u => u.name === user.name))
.filter(index => index > 0)
.map((i => { return { [i]: true} }));
console.log(result)

Get most Senior

friends!
I need your help.
A list of information about people is given.
An array containing the oldest person in the list must be returned. If several people are of the same highest age, then an array should be returned containing all of them.
The age is stored in the "age" field.
Input data:
const data =[
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
]
const result = getMostSenior(data);
Output data:
console.log(result);
// [
// { firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
// { firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
// ]
My try:
const getMostSenior = humans => {
let oldestHuman = humans.reduce((oldest, human) => {
return oldest.age > human.age ? oldest : human;
})
return oldestHuman
};
But this only returns an array containing the oldest person in the list.
Can't figure out how to return an array where multiple people have the same maximum age.
Please, help.
This is not an efficient implementation though!
function getMostSenior(data){
const ageArray = [];
const agedPersons = {};
data.forEach((item)=>{
const age = item.age;
ageArray.push(age);
if(agedPersons.hasOwnProperty(age)){
agedPersons[age].push(item);
}
else{
agedPersons[age] = [];
agedPersons[age].push(item);
}
});
ageArray.sort();
return [...agedPersons[ageArray[ageArray.length-1]]];
}
Instead of pushing the object to the accumulator you should return only the age. You can then use filter on the data to get all those objects where the age matches the value of that variable.
const data=[{firstName:"Gabriel",lastName:"X.",country:"Monaco",continent:"Europe",age:49,language:"PHP"},{firstName:"Odval",lastName:"F.",country:"Mongolia",continent:"Asia",age:38,language:"Python"},{firstName:"Emilija",lastName:"S.",country:"Lithuania",continent:"Europe",age:19,language:"Python"},{firstName:"Sou",lastName:"B.",country:"Japan",continent:"Asia",age:49,language:"PHP"}];
function getMostSenior(data) {
const oldest = data.reduce((oldest, c) => {
return c.age > oldest ? c.age : oldest;
}, 0);
return data.filter(obj => obj.age === oldest);
}
console.log(getMostSenior(data));
The alternative to using reduce for this task would be to use a for...of loop to iterate over the array and update a variable if the age value of an object is greater than the current value of the variable.
const data=[{firstName:"Gabriel",lastName:"X.",country:"Monaco",continent:"Europe",age:49,language:"PHP"},{firstName:"Odval",lastName:"F.",country:"Mongolia",continent:"Asia",age:38,language:"Python"},{firstName:"Emilija",lastName:"S.",country:"Lithuania",continent:"Europe",age:19,language:"Python"},{firstName:"Sou",lastName:"B.",country:"Japan",continent:"Asia",age:49,language:"PHP"}];
function getMostSenior(data) {
let oldest = 0;
for (const { age } of data) {
if (age > oldest) oldest = age;
}
return data.filter(obj => obj.age === oldest);
}
console.log(getMostSenior(data));
I think this is little optimal way to solve your problem using Array Reduce
var data =[
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
var output = data.reduce((a, c) => {
if (a.length) {
if (a[0].age < c.age)
a = [c];
else if (a[0].age == c.age)
a.push(c)
} else {
a = [c];
}
return a;
}, []);
console.log(output);

How to check whether various number ranges are represented in a one-dimensional array of objects?

I am attempting to check whether all age groups from teen to centenarian are represented in an array.
My logic path has been:
Create an array with pre-defined decade-based age brackets [1, 2, 3, ... , 10]
Isolate the age value of each element in the sample array of objects
Divide those ages by 10 to get what decade the age falls in
parseInt that number to get an integer and put resultant figures in new array
Compare that array with the pre-defined age bracket array created initially.
The expected output is true but I am instead getting false.
Another logic issue I am facing is that the oldest age in the sample array, 128, reduces to 12 after dividing/parsing whereas it would be preferable for it to check if the int is > 10 instead of specifically 10.
Code below:
const devAges = list.map((list) => {
return list.age
})
const devAgesDiv = devAges.map(i => i / 10);
for(i = 0; i < devAgesDiv.length; i++){
devAgesDiv[i] = parseInt(devAgesDiv[i]);
}
function allAges(list) {
const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
return ageBrackets.every((ageBracket) =>
list.some((listItem) => listItem.ageBracket === ageBracket)
);
}
console.log(allAges(list)); // output false;
Sample array below:
var list = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
{ firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
{ firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
{ firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
{ firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];
You can make two updates to get the desired result:
devAgesDiv - check if the list age is over 100 and return 10 otherwise divide by 10; you can parseInt the result of that test
You can use includes in allAges to check every ageBracket is represented
See below:
const list = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
{ firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
{ firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
{ firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
{ firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];
const devAgesDiv = list.map(item => parseInt(item.age > 100 ? 10 : item.age / 10));
const ageBrackets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function allAges(list) {
return ageBrackets.every(ageBracket => list.includes(ageBracket));
}
console.log(allAges(devAgesDiv)); // true

Group by array object by object

I have an array of object like that :
[{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
And i would like group by the city, like below:
[{name: 'Peter', age: '22', hobby: 'soccer', cities: ['london', 'Paris']},
{name: 'Mario', age: '30', hobby: 'bike',cities: ['Paris', 'Madrid']},
{name: 'Rick', age: '28', hobby: 'tennis', cities: ['Berlin']}]
I try with this function by, I don't have the good array
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].city;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(arrayPeople[i].city);
}
let arrayGroupBy= [];
for (let groupName in groups) {
arrayGroupBy.push({ ...arrayPeople, cities: groups[groupName] });
}
How I can make my group by ?
Thank for your help.
You can use Array.reduce to process your input array, using the name, age and hobby as a key to create a grouping object, and adding the city for each key to an array in that object. You can then use Object.values to grab just the values from the grouping object into an array:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { city, ...rest }) => {
let key = Object.values(rest).join('#');
c[key] = c[key] || { ...rest, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note the above code is dependent on the properties in the objects being in the same order in each object (in the sample data, name, age, hobby). If this might not be the case, you will need to create the key using the named properties instead, for example:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ age: '30', hobby: 'bike', name: 'Mario', city: 'Paris' },
{ name: 'Peter', hobby: 'soccer', city: 'Paris', age: '22' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { name, age, hobby, city}) => {
let key = `${name}#${age}#${hobby}`;
c[key] = c[key] || { name, age, hobby, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note also that all the above code is dependent on choosing a delimiter (I've used #) that will not occur in the name or hobby values. If there is no suitable delimiter character, then it is safer to use something like JSON.stringify to produce the key value e.g. for the second code block you would use:
let key = JSON.stringify([name, age, hobby]);
Your approach is pretty near to the correct solution. You are grouping persons by city. You have to turn around and group cities by person
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].name;
if (!groups[groupName]) {
groups[groupName] = {name: arrayPeople[i].name, age: arrayPeople[i].age, hobby: arrayPeople[i].hobby, cities: []};
}
groups[groupName].cities.push(arrayPeople[i].city);
}
console.log(Object.values(groups));
This is TypeScript so I'd probably come up with the type corresponding to the final array elements: that is, remove the city property and add a cities property:
type PersonCities = Omit<typeof arrayPeople[number], "city"> & { cities: string[] };
Then you want to put all your objects into a dictionary keyed by whatever you want the grouping condition to be (converted into a string):
const peopleCities: Record<string, PersonCities> = {};
for (let p of arrayPeople) {
const { city, ...person } = p;
const groupByKey = JSON.stringify([person.name, person.hobby, person.age]);
if (!(groupByKey in peopleCities)) {
peopleCities[groupByKey] = { ...person, cities: [] };
}
peopleCities[groupByKey].cities.push(city);
}
const arrayPeopleCities = Object.values(peopleCities);
Here we're making the grouping key a JSON string of the name, hobby, and age properties in an array. And some object rest/spread syntax to copy people properties around without too much redundancy.
Playground link to code

Is it possible to iterate over the array, excluding the first element?

Is it possible to iterate over the array, excluding the first element (omit the first object in the array)?
CODE:
let multipleDemo =[];
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' },
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }
];
for(var i =0; i < people.length; i++) {
multipleDemo.push(people[i]);
people.splice(people[i], 1000);
console.log(multipleDemo);
console.log(people);
}
Example code: https://plnkr.co/edit/UJfRUs6dAT1NC1EnOvqA?p=preview
I want to leave { name: 'Adam', email: 'adam#email.com', age: 12, country: 'United States' } in array people. Rest of elements I want to put in array multipleDemo
I want such as FINISH EFFECT:
let multipleDemo =[,
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }];
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' }
];
You can use Array.prototype.slice() to modify your arrays to get your desired output.
let people = [{
name: 'Adam',
email: 'adam#email.com',
age: 12,
country: 'United States'
},
{
name: 'Amalie',
email: 'amalie#email.com',
age: 12,
country: 'Argentina'
},
{
name: 'Estefanía',
email: 'estefania#email.com',
age: 21,
country: 'Argentina'
},
{
name: 'Adrian',
email: 'adrian#email.com',
age: 21,
country: 'Ecuador'
},
{
name: 'Wladimir',
email: 'wladimir#email.com',
age: 30,
country: 'Ecuador'
},
{
name: 'Samantha',
email: 'samantha#email.com',
age: 30,
country: 'United States'
},
{
name: 'Nicole',
email: 'nicole#email.com',
age: 43,
country: 'Colombia'
},
{
name: 'Natasha',
email: 'natasha#email.com',
age: 54,
country: 'Ecuador'
},
{
name: 'Michael',
email: 'michael#email.com',
age: 15,
country: 'Colombia'
},
{
name: 'Nicolás',
email: 'nicolas#email.com',
age: 43,
country: 'Colombia'
}
];
let multipleDemo = people.slice(1);
people = people.slice(0, 1);
console.log(multipleDemo);
console.log('--------------------');
console.log(people);
You can use Array Destructuring to unpack and assign remaining part of the array to a variable using rest pattern and use .forEach() to iterate over them as follows:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const [first, ...rest] = arr;
rest.forEach(v => console.log(v));
.as-console-wrapper { max-height: 100% !important; top: 0; }
There are many ways to achieve this. but the easiest and concise solution would be using the filter(). Which returns an array that contains each element where the condition is met.
let people = [
{ name: 'Adam', email: 'adam#email.com', age: 12,
country: 'United States' },
{ name: 'Amalie', email: 'amalie#email.com', age: 12,
country: 'Argentina' },
{ name: 'Estefanía', email: 'estefania#email.com', age: 21,
country: 'Argentina' },
{ name: 'Adrian', email: 'adrian#email.com', age: 21,
country: 'Ecuador' },
{ name: 'Wladimir', email: 'wladimir#email.com', age: 30,
country: 'Ecuador' },
{ name: 'Samantha', email: 'samantha#email.com', age: 30,
country: 'United States' },
{ name: 'Nicole', email: 'nicole#email.com', age: 43,
country: 'Colombia' },
{ name: 'Natasha', email: 'natasha#email.com', age: 54,
country: 'Ecuador' },
{ name: 'Michael', email: 'michael#email.com', age: 15,
country: 'Colombia' },
{ name: 'Nicolás', email: 'nicolas#email.com', age: 43,
country: 'Colombia' }
];
let multipleDemo = people.filter((v, k) => k !== 0);
people = people.filter((v, k) => k === 0);
console.log(multipleDemo)
console.log(people)
You can use .slice() to omit n elements from the beginning.
Array.slice(1) means you take the array starting from index 1 to the end.
You can also define until which element you want to slice off.
Array.slice(1, 3) will slice the elements of index 1 and 2. It will be Amalie and Estefanía in this case.
let people = [
{ name: "Adam", email: "adam#email.com", age: 12, country: "United States" },
{ name: "Amalie", email: "amalie#email.com", age: 12, country: "Argentina" },
{ name: "Estefanía", email: "estefania#email.com", age: 21, country: "Argentina" },
{ name: "Adrian", email: "adrian#email.com", age: 21, country: "Ecuador" },
{ name: "Wladimir", email: "wladimir#email.com", age: 30, country: "Ecuador" },
{ name: "Samantha", email: "samantha#email.com", age: 30, country: "United States" },
{ name: "Nicole", email: "nicole#email.com", age: 43, country: "Colombia" },
{ name: "Natasha", email: "natasha#email.com", age: 54, country: "Ecuador" },
{ name: "Michael", email: "michael#email.com", age: 15, country: "Colombia" },
{ name: "Nicolás", email: "nicolas#email.com", age: 43, country: "Colombia" }
];
let multipleDemo = people.slice(1);
multipleDemo.forEach(function (current) {
console.log(current.name);
});
Since you simply want to copy the elements from people array to multipleDemo array excluding the first element, you could use slice() array method.
multipleDemo = people.slice(1)
.slice(1) will copy the contents of people array from index1 without reference to the multipleDemo array.
.slice() in MDN

Categories

Resources