Filter Array by First Letter of String Property

Filter array by first letter of string property

Try with following code

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF like %@", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];

EDITED :

NSPredicate pattern should be:

NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];

How can I filter an array based on the first letter of a contained property?

There are at least two reasons why your code does not give the expected result:

  • The index you work with, points to the index in the original array. As your new array will have more elements, it makes no sense to use that index for a splice on the new array. It will be pointing to the wrong place eventually;

  • You only push the prev element, so the last element will never be pushed to the result array

I would suggest to use reduce with a accumulated value (first argument of the callback) that will build up the final array. To remember the last letter object that was introduced, I will pair this accumulated value with that letter. So I'll work with an array that contains two elements:

  • The final array being accumulated
  • The letter of the most recently added letter object

Then the final result will be taken from the first element of that array, ignoring the second value.

I suggest not to work with character codes, but just with the characters. It saves you from converting the code back to a character.

Here is the code:

var list = [    {name: '4 Arn', isLetter: false},    {name: 'Abax', isLetter: false},    {name: 'Aramex', isLetter: false},    {name: 'Booking', isLetter: false},    {name: 'Dangerous', isLetter: false},    {name: 'Manali', isLetter: false}];
var newArr = list.reduce(function(collect, cur, index, originalArrray) { var currentChar = cur.name.toUpperCase().substr(0,1); if (currentChar < 'A') currentChar = '#'; if (collect[1] != currentChar) { collect[0].push({isLetter: true, letter: currentChar}); collect[1] = currentChar; } collect[0].push(cur); return collect;}, [[], null])[0];
// outputconsole.log(newArr);

Filter array by first letter

There is an array_filter() function in PHP which you can use to accomplish this:

$filtered = array_filter($array, create_function('$a', 'return $a[0] == "' . $letter . '";'));

I'll leave it to you to generalize the function to handle all the letters.

See: http://www.php.net/manual/en/function.array-filter.php

Filter array by letter

You can define your own filter function :

function filter(names, index, letter) {
var filteredNames = names.filter(function(word) {
return word.charAt(index) === letter;
});
return filteredNames;
}

Group array of strings by first letter

I ran your code as well as the test examples provided by JS challenger. I noticed that they where case sensitive. So although your code works well, if the words begin with upper case it will not pass certain cases. Attached is my version that passed all test examples.

If you add : .toLowerCase to the firstChar, I believe you will pass as well. Happy coding ;)

P.S if the image below does not work please let me know, I am just learning how to contribute to Stack Exchange, thanks.

const groupIt = (array) => {
let resultObj = {};

for (let i =0; i < array.length; i++) {
let currentWord = array[i];
let firstChar = currentWord[0].toLowerCase();
let innerArr = [];
if (resultObj[firstChar] === undefined) {
innerArr.push(currentWord);
resultObj[firstChar] = innerArr
}else {
resultObj[firstChar].push(currentWord)
}
}
return resultObj
}

console.log(groupIt(['hola', 'adios', 'chao', 'hemos', 'accion']))

console.log(groupIt(['Alf', 'Alice', 'Ben'])) // { a: ['Alf', 'Alice'], b: ['Ben']}

console.log(groupIt(['Ant', 'Bear', 'Bird'])) // { a: ['Ant'], b: ['Bear', 'Bird']}
console.log(groupIt(['Berlin', 'Paris', 'Prague'])) // { b: ['Berlin'], p: ['Paris', 'Prague']}

search or filter data based on first letter match

You only need to modify your customSearchFunction to:

 customSearchFn(term: string, item: any) {
// check if the name startsWith the input, everything in lowercase so "a" will match "A"
return item.name.toLowerCase().startsWith(term.toLowerCase())
}

Working stackblitz

FYI, the custom function is called with every item on your list.

How to filter an array of objects based on the first character of a property in the array of object?

itemSplit is an array. You need to get the first element of it, and parse it to an integers.

In the filter() call, you shouldn't check f.RowNumber === firstItem.RowNumber since you only care about the part before . in f.rowNumber. Parse the first part of this, and compare it with the number you're searching for.

(function() {
const ds = [{
ID: 1,
RowNumber: "1"
},
{
ID: 2,
RowNumber: "1.01"
},
{
ID: 3,
RowNumber: "1.02"
},
{
ID: 4,
RowNumber: "1.03"
},
{
ID: 5,
RowNumber: "2.01"
}
];

const gridDs = [{
ID: 1,
RowNumber: "1",
Name: "Box 1"
},
{
ID: 2,
RowNumber: "1.01",
Name: "Box 2"
},
{
ID: 3,
RowNumber: "1.02",
Name: "Box 3"
},
{
ID: 4,
RowNumber: "1.03",
Name: "Box 4"
},
{
ID: 5,
RowNumber: "",
Name: ""
},
{
ID: 6,
RowNumber: "2",
Name: ""
},
{
ID: 7,
RowNumber: "2.01",
Name: "Box 7"
},
{
ID: 8,
RowNumber: "2.02",
Name: "Box 8"
},
{
ID: 9,
RowNumber: "3",
Name: "Box 9"
},
];
const firstItem = ds[0];
const searchNumber = parseInt(firstItem.RowNumber.split(".")[0]);
const foundItems = gridDs.filter(f => parseInt(f.RowNumber.split(".")[0]) === searchNumber);

console.log(foundItems);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to filter strings from an array excluding the longest string?

The callback of your filter does not return a value.

Either use

const allButTheLongest = students.filter(name => name != longestName)

or

const allButTheLongest = students.filter(function(name){
return name != longestName;
})


Related Topics



Leave a reply



Submit