How to filter the matched element at top index in an array in JS

javascript filter array of objects by another array of objects
javascript filter array of objects by key
javascript filter array multiple values
javascript array.filter multiple arguments
array filter javascript
javascript array contains
filter array of arrays javascript
array map javascript

I have a list of array as follows:

 var arr = ['Ashwin Rathod','Basker Babu','Cherry Spanish','Dravid Mukund'];

I have a search box and If I search for 'Mukund',then I should show all the results provided the string which contains 'Mukund' should come at top but in my case all the results are coming in alphabetical order(from backend).I did that using array.filter but I want to do it in any other best way.Can anyone please suggest me help.Thanks.

This is what I tried,

function filterResults() {
  const matchedJobList = [],
        unMatchedJobList = [];

  arr.filter(function(job) {
    if (job.toUpperCase().includes(mySearchedString.toUpperCase())) {
      matchedJobList.push(job);
    } else {
      unmatchedJobList.push(job);
    }
  });

  return [...matchedJobList, ...unmatchedJobList];
}

result:

['Dravid Mukund','Ashwin Rathod','Basker Babu','Cherry Spanish'];

I got the result as expected but hoping to get the best method to do it.


An alternative could be the function reduce + unshift in order to add the target strings at the first indexes of the array.

let arr = ['Ashwin Rathod','Basker Babu','Cherry Spanish','Dravid Mukund'],
    target = 'Mukund',
    result = arr.reduce((a, c) => {
      if (c.toUpperCase().includes(target.toUpperCase())) a.unshift(c);
      else a.push(c);
      return a;
    }, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array.prototype.filter(), let newArray = arr .filter( callback ( element [, index , [ array ]])[, thisArg ]) following code at the beginning of your scripts, allowing use of filter()� The filter() method creates a new array with all the elements that pass the test implemented by the callback() function. Internally, the filter() method iterates over each element of the array and pass each element to the callback function. If the callback function returns true, it includes the element in the return array.


If you don't mind the potential change of unmatched items order then you can go for sort function:

function filterResults() {
    const sorderArray = [...arr];
    sorderArray.sort(item => item.toUpperCase().indexOf(mySearchedString.toUpperCase()) !== -1 ? -1 : 1);

    return sorderArray;
}

Sort function works directly on the array so I'm creating a copy of the arr to prevent it's mutation.

JavaScript Array Filter: Filtering Array Elements Based on a Test , Home / JavaScript Tutorial / JavaScript Array filter: Filtering Elements function callback(currentElement, index, array){ // . return value >= this.lower && value < = this.upper; } let data = [10, 20, "30", 1, 5, 'JavaScript filter', undefined, Basic Regular Expressions � search() � match() � replace() � Character Classes � Anchors � Get element's index after using filter. Ask Question Asked 6 years, 9 months ago. But how can i know what is the index of this element in it's original array?


That is not filtering, that is sorting.

const arr = ['Ashwin Rathod', 'Basker Babu', 'Cherry Spanish', 'Dravid Mukund'];
const mySearchedString = 'Mukund';

function filterResults() {
  const clonedResults = [...arr];
  return clonedResults.sort((job1, job2) => {
    const job1match = job1.toUpperCase().includes(mySearchedString.toUpperCase());
    const job2match = job2.toUpperCase().includes(mySearchedString.toUpperCase());
    if (job2match && !job1match) return 1;
    return 0;
  });
}


console.log(filterResults());

Array .filter() Method ― Scotch.io, The array .filter() method iterates through a given array and returns a new array which matches a rule or test passed as parameter to the method. The filter() method returns an array containing elements of the parent array that match const filteredArray = oldArray.filter(callbackFunction(element[,index[,array]])[, thisArg])� The filter () method creates a new array with all elements that pass the test implemented by the provided function. You can use forEach. The filter () method creates a new array with all elements that pass the test implemented by the provided function. $scope.indexOfField = function(fieldId) { var i; return $scope.model.fieldData.forEach(function(x, index) { if (x.Id === fieldId) { i = index; } }); // use i }


We can move founded element to the top:

let arr = ['Ashwin Rathod','Basker Babu','Cherry Spanish','Dravid Mukund'],
search = 'Mukund';


arr.forEach((element, ind) => {
  if (element.indexOf(search))
    arr.unshift(arr.splice(ind, 1)[0]);
});
console.log(arr);

JavaScript Array filter() Method, A function to be run for each element in the array. Function arguments: Argument, Description. currentValue, Required. The value of the current element. index� array1's elements is used as conditions to filter out elements in array2. For instance: array1= [apple, grapes, oranges] array2= [potato, pears, grapes, berries, apples, oranges] After feeding into a function, array2 should have elements as such: filter_twoArrays(array1,array2) array2= [grapes, apples, oranges]


Using splice()

const arr = ['Ashwin Rathod', 'Basker Babu', 'Cherry Spanish', 'Dravid Mukund']
const search = 'Mukund'

const index = arr.findIndex(e => e.includes(search))

console.log([...arr.splice(index, 1), ...arr]);

4 Methods to Search Through Arrays in JavaScript ← Alligator.io, The main difference is, filter() always returns an array, even if there is only one matching element. But it will return all the matching elements, whereas find() Do you need to find the index of the element? Using array.splice(): The array.splice() method is usually used to add or remove items from an array. This method takes in 3 parameters, the index where the element id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted.


9 Ways To Remove 🗑 Elements From A JavaScript Array [Examples], The JavaScript Array filter method to create a new array with desired items, a more from a specific Array index; filter - allows you to programatically remove elements from an Array Removing Elements from Beginning of a JavaScript Array It uses Array.filter to return elements not matching a value. The indexOf() method searches the array for the specified item, and returns its position. The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array. Returns -1 if the item is not found.


.filter(), Description: Reduce the set of matched elements to those that match the selector We can also take advantage of the index passed through the function, which resulting jQuery object only if it matches one of the nodes in the filtering array. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. Syntax: array.filter(callback(element, index, arr), thisValue) Parameters: This method accepts five parameter as mentioned above and described below:


Array methods, Here we can see that splice returns the array of removed elements: The syntax is similar to find , but filter returns an array of all matching elements: let results = arr . filter ( function ( item , index , array ) { // if true item is pushed as a standalone function, with this=undefined , thus leading to an instant error. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help of . Approach: Initialize an array. Select the targetd index with the help of .map and .filter methods. Set the new value at targeted index; Syntax: