sort array of objects based on string - javascript

Suppose we have an array like
var a = [
{ name: 'Tom', surname: 'TestAsIvanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' }
]
I need to sort this array by surname field based on a provided string, e.g.:
for 'iva' the pattern array should be sorted as follows
var newA = [
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'John', surname: 'Alivanov' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
for 'a' the pattern array should be sorted as follows
var newA = [
{ name: 'John', surname: 'Alivanov' },
{ name: 'Ivan', surname: 'Ivanov' },
{ name: 'Kate', surname: 'Ivanova' },
{ name: 'Tom', surname: 'TestAsIvanov' },
]
So arrays should be ordered by string pattern provided. How is it possible to implement this?

I've made a simple sort script for that. I don't know if it is the best way because I had to use two sort() methods, one to sort alphabetically(taken from here) and another to simulate a LIKE 'string%'(comparing to SQL) to get your condition:
var queryString = "iva";
a = a.sort(function(a, b) {
var s1 = a.surname.toUpperCase().indexOf(queryString.toUpperCase());
var s2 = b.surname.toUpperCase().indexOf(queryString.toUpperCase());
return (s1 > -1 && s1 > s2);
});
Fiddle with full code
At least it worked with both examples you provided, but I'm not sure if it is all you need.

Related

Copy values from multiple keys from array of object

I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
let values=[];
users && users.map(user => {
values.push(user['name'])
values.push(user['age'])
})
console.log(values);
output
['John', 34, 'Wayne', 44, 'David', 24]
You can bind each items to an array containing both its name and age and then flattern these arrays.
This can be done using Array#FlatMap
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
const nameAndAges = users.flatMap(user => [user.name, user.age])
console.log(nameAndAges)
Your solution looks good, this can be also solved in different ways, I guess you may want to create function for handling this.
const users = [
{ id: 0, name: 'John', age: 34 },
{ id: 1, name: 'Wayne', age: 44 },
{ id: 2, name: 'David', age: 24 },
];
const result = mapArrayToProps(users, ['name', 'age']);
function mapArrayToProps(arr, props) {
return arr.flatMap(obj => mapObjectToProps(obj, props));
}
function mapObjectToProps(obj, props) {
return props.map(prop => obj[prop])
}
console.log(result);

How to get the list of occurence in list of object reactjs

I'm having trouble with arrays of object in React.js. I have a list of objects like this :
const list = [
{ name: name1,
age: age1,
address: addresse1
},
{ name: name2,
age: age2,
address: addresse2
},
{ name: name1,
age: age1,
address: addresse4
},
{ name: name3,
age: age3,
address: addresse3
}]
How can I get an array with every different names like that ?
['name1','name2','name3']
I tried by mapping the list and set a bool but I can't figure how to loop and compare list[i] and list[i+1] in mapping function
You can map array to make an array of names and after that leave only unique values
const list = [
{ name: 'name1',
age: 'age1',
address: 'addresse1'
},
{ name: 'name2',
age: 'age2',
address: 'addresse2'
},
{ name: 'name1',
age: 'age1',
address: 'addresse4'
},
{ name: 'name3',
age: 'age3',
address: 'addresse3',
}]
const result = [...new Set(list.map(item => item.name))]
console.log({ result })

Filtering object keys inside an array of objects

Let's assume I'm obtaining an array of objects from a Node Repository, for example:
results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
How can I filter every object taking only the keys I need, for example avoiding 'age' key?
filteredResults = [
{
name: "John",
surname: "Fool",
},
{
name: "Erik",
surname: "Owl",
}
]
I've already obtained this by creating another empty array and populating it by looping on the original one, but in case of large-data this would be heavy.
repository.retrieve((error, result) => {
let filteredData = [];
result.forEach(r => {
filteredData.push({
name: r.name,
description: r.description,
});
});
});
In SQL, I would obtain it this way:
SELECT `name, description` FROM results;
You can just rebuild the object as you want
{
name: rec.name,
surname: rec.surname
}
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
return {
name: rec.name,
surname: rec.surname
}
})
console.log(result)
Or delete fields that is useless
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
delete rec.age
return rec
})
console.log(result)
I suggest you can tell more about what you will need to perform on the output to get the answer that can help.
Case 1. if your original list will survive and you accept your "modified list" to always follow the original list, you may use a generator to wrap your original object, by always not returning those extra properties.
Case 2. if you really want a query system, you may try using real DB thing such as levelDB
Case 3. if you need to display the modified list, write a simple wrapper to fit the format of each list item
Case 4. if you need to snapshot the modified list as object, the method you already made is already a very reasonable method
Case 5. if you need to snapshot the modified list as another output, you can try to directly obtain such output rather than making the intermediate object
You can use map and reduce to simplify this, which obviates the need to create a new array.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
let keys = ['name', 'surname'];
var filtered = results.map(obj=>
keys.reduce((acc,curr)=>(acc[curr]=obj[curr],acc), {}));
console.log(filtered);
You can also use object destructuring.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
var filtered = results.map(({name,surname})=>({name,surname}));
console.log(filtered);
Take a look at Array.map.It creates the transformed array.
let arr = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
let result = arr.map((elem) => {
return {
name: elem.name,
surname: elem.surname
}
});
console.log(result);
You can use Array.map() to transform individual elements of the array. And in the callback function use Object destructuring assignment to use only the keys you are interested in and return a new object with only those keys.
let results = [
{ name: "John", surname: "Fool", age: 22 },
{ name: "Erik", surname: "Owl", age: 38 }
];
let modified = results.map(({name, surname}) => ({name, surname}));
console.log(modified);

Native filter in JavaScript with objects?

To give background of the prompt (this isn't homework, but some questions that someone forwarded me to help with understanding how to use HOF and implementing them correctly so all explanations as well as different approaches to the problem are welcomed):
a) Implement a findPerson method that takes an Array of people and a name String as the target. Each person Object is structred:
{name: 'Erika', gender: 'Female'}
usage example:
findPerson(people, 'Erika') // -> {name: 'Erika', gender: 'Female'}
Constraint: Use filter
My array of objects is as follows:
var people = [
{
name: 'Max',
gender: 'Trans'
},
{
name: 'Sue',
gender: 'Female'
},
{
name: 'Jake',
gender: 'Male'
},
{
name: 'John',
gender: 'Male'
},
{
name: 'Erika',
gender: 'Female'
}
];
The code that I have constructed thusfar is this:
const findPerson = (people, name) => {
people.filter(function(person) {
if(person.name === name){}
return person;
});
};
The problem is that I am running into this error as follows:
should return an object ‣TypeError: Cannot read property 'should' of undefined
should return the proper object ‣TypeError: Cannot read property 'should' of undefined
If anyone could be of assistance of pointing me in the right direction as to how to go about my logic of solving this and where did I go wrong in my code?
filter function should return true or false:
var people = [
{name: 'Max', gender: 'Trans'},
{name: 'Sue', gender: 'Female'},
{name: 'Jake', gender: 'Male'},
{name: 'John', gender: 'Male'},
{name: 'Erika', gender: 'Female'}
];
const findPerson = (people, find) => people.filter(({name}) => name === find)[0];
console.log(findPerson(people, 'Erika'))
const people = [{
name: 'Max',
gender: 'Trans'
},
{
name: 'Sue',
gender: 'Female'
},
{
name: 'Jake',
gender: 'Male'
},
{
name: 'John',
gender: 'Male'
},
{
name: 'Erika',
gender: 'Female'
}
];
const findPerson = (persons, name) => {
return persons.filter((person) => person.name === name);
};
console.log(findPerson(people, 'Erika')[0]);
The issue with your code is that you were not returning the value of calling filter.
filter after it has run, returns an array. It's that returned array that will contain the value that was filtered out.
I did this: findPerson(people, 'Erika')[0] to select the first item from the array since the return value of filter is an array.

Combining two arrays based on properties

I have two arrays,
let student = [{ id: "weqwe", name: "john" }, { id: "wqeqweq", name: "doe" }]
let details = [
{ id: "2qweqweq", name: "larry", oName: "john" },
{ id: "231234qa", name: "jacob", oName: "john" },
{ id: "wetyrqwte", name: "jane", oName: "doe" }
]
I need to check through each object in details array and compare it with student array (compare with oName property in details array with name property in student array) and need to add an array of the details as on object property. Also need to remove the oName, I have tried in es6 but dynamically creating array and pushing gives only the last value, Please see the below expected output,
let output = [
{
id: "weqwe",
name: "john",
details: [
{ id: "2qweqweq", name: "larry" },
{ id: "231234qa", name: "jacob" }
]
},
{
id: "wqeqweq",
name: "doe",
details: [
{ id: "wetyrqwte", name: "jane" }
]
}
]
Thanks in advance !!
try this:
let student = [{ id: "weqwe", name: "john" }, { id: "wqeqweq", name: "doe" }]
let details = [
{ id: "2qweqweq", name: "larry", oName: "john" },
{ id: "231234qa", name: "jacob", oName: "john" },
{ id: "wetyrqwte", name: "jane", oName: "doe" }
];
let output = [{
id: "weqwe",
name: "john",
details: [
{ id: "2qweqweq", name: "larry" },
{ id: "231234qa", name: "jacob" }
]
},
{
id: "wqeqweq",
name: "doe",
details: [
{ id: "wetyrqwte", name: "jane" }
]
}
];
let result = student.map((obj) => {
obj.details = details.filter(o => o.oName === obj.name).map(({oName,...other}) =>other);
return obj;
});
console.log(result);
let student = [{id:"weqwe", name:"john"}, {id:"wqeqweq", name:"doe"}]
let details = [
{id:"2qweqweq", name:"larry", oName:"john"},
{id:"231234qa", name:"jacob", oName:"john"},
{id:"wetyrqwte", name:"jane", oName:"doe"}
]
let output= student.map(student=> {
const detailsObj = details.filter(({oName})=> oName === student.name)
return {...student, details: detailsObj.map(({oName, ...other})=> other)}
})
console.log(output)

Categories

Resources