I am completing a homework assignment where I will have to filter an array into a new array for a vehicle with the term of “ford” in it. The assignment wants the format to be in ES6 using the arrow function syntax so something like
const arr = [
{name: “Honda”, type: “Accord”},
{name: “ford”, type: “fusion”},
{name: “Toyota”, type: “Camry”}
]
const newArr = [...arr].filter(value => value === ‘ford’);
Console.log(newArr);
I know this is incorrect and wouldn’t actually get the name of the vehicle that has “ford” in it but I’m giving an example on how they would want it formatted.
You need value.name also check the quotes. In this case there may not be any use of the spread operator
const arr = [{
name: 'Honda',
type: 'Accord'
},
{
name: 'ford',
type: 'fusion'
},
{
name: 'Toyota',
type: 'Camry'
}
]
const newArr = arr.filter(value => value.name === 'ford');
console.log(newArr);
Related
Im having trouble creating an array that contains unique subset of a larger array, please help!
Original Array allMembers (6)[{},{},{},{},{},{}]
allMembers Payload: 0:{id:1, name: Alex} 1:{id:2, name: James} 2:{id:3, name: Bob} 3:{id:4, name: lara} 4:{id:5, name: Dan} 5:{id:6, name: Jes}
Second array uniqueMembers (3)[{},{},{}]
uniqueMembers Payload: 0:{id:1, name: Alex} 1:{id:2, name: James} 2:{id:3, name: Bob}`
what I'm looking for is to find the users that are in allMembers but not in uniqueMembers
so my desired new array output would be the following array resultArray
resultArray (3)[{},{},{}]
resultArray Payload: 0:{id:4, name: lara} 1:{id:5, name: Dan} 2:{id:6, name: Jes}
My attempt
for(let m=0; m<allMembers.length;m++)
{
console.log('Testing include statement', uniqueMembers.includes(allMembers[m])) //output always false
if(uniqueMembers.includes(allMembers[m]))
{
console.log('ITS ALREADY IN: ', allMembers[m])
}else{
this.setState((prevState) => ({
resultArray: [...prevState.resultArray, allMembers[m]]
}));
console.log('ITS NOT IN: ', allMembers[m])
}
}// resultArray ends up the same as allMembers :(
Any feedback on how I can get the desired resultArray values would be appreciated!
Build an associative array to efficiently lookup if a member should be filtered out.
lookup = {}
for (const um uniqueMembers)
lookup[um.id] = 1;
resultArray = allMembers.filter( mem => !lookup.hasOwnProperty(mem) );
Two solutions posted after this one suggested using filter and some. Those solutions are O(N2). This one is should be O(N), which is way better.
If your unique array is very huge as well, convert unique array to one set first, it will save time to loop the unique array to check the match.
Then uses Array.filter to get the not in unique elements.
let all = [{id:1, name: 'Alex'}, {id:2, name: 'James'},{id:3, name: 'Bob'},{id:4, name: 'lara'},{id:5, name: 'Dan'} ,{id:6, name: 'Jes'}]
let unique = [{id:2, name: 'James'},{id:3, name: 'Bob'}]
function getNotInUnique(src, target) {
let uniqueSet = new Set(target.map(member => member.id))
return src.filter(member => !uniqueSet.has(member.id))
}
console.log(getNotInUnique(all, unique))
You can use filter along with some.
const allMembers = [
{id:1, name: 'Alex'},{id:2, name: 'James'},{id:3, name: 'Bob'}, {id:4, name: 'lara'}, {id:5, name: 'Dan'}, {id:6, name: 'Jes'}
];
const uniqueMembers = [
{id:1, name: 'Alex'},{id:2, name: 'James'},{id:3, name: 'Bob'}
];
const res = allMembers.filter(m => !uniqueMembers.some(({id})=>m.id===id));
console.log(res);
I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )
I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.
Basically, I want to compare some objects and re-group if the value of specific property is matched.
As following code, If types are same, I want to regroup as one array of object.
var obj = [{id: 94 , type: 'silver'}, {id:95,type:'gold'} , {id:96, type: 'silver'} ]
return newObj = [{id: 94 , type: 'silver'},{id:96, type: 'silver'} ]
I would like to use lodash or underscore If It’s possible.
Anyone have great idea? Thanks.
Do you want something like this? https://jsbin.com/negeqineje/edit?js,console
var metals = [
{id: 94 , type: 'silver'},
{id: 95, type:'gold'},
{id: 96, type: 'silver'},
{id: 97, type: 'platinum'},
];
var grouped = metals.reduce(function (grouped, metal) {
grouped[metal.type] = metals.filter(function (_metal) {
return (metal.type === _metal.type);
});
return grouped;
}, {});
I have the below array. I am attempting to exclude certain objects from this array in processing.
For example. I would like to exclude the type 'dog' and only use any object that is of type duck.
I'd like to do this using underscore/lodash but will use plain JS if need be.
animals: [
{
type: 'duck',
name: 'quack',
},
{
type: 'duck',
name: 'quieck',
},
{
type: 'dog',
name: 'bark',
},
]
The Underscore/LoDash way, would be just
var result = _.where(animals, {type: 'duck'});
I suppose your array represents variable animals. You can use Array.prototype.filter() function. If you want all ducks:
const animals = [
{ type: 'duck', name: 'quack' },
{ type: 'duck', name: 'quieck' },
{ type: 'dog', name: 'bark' },
];
const ducks = animals.filter(o => o.type === 'duck');
or if you want to exclude all dogs:
const withoutDogs = animals.filter(o => o.type !== 'dog');
I used ES6 syntax. ES5 equivalent would be:
var ducks = animals.filter(function(o) { return o.type === 'duck' });