简体   繁体   中英

reorder an array elements based on first phrase in pattern of elements

I have a pairs array consist of an specific pattern (first phrase = second phrase). I want to reorder the pairs array based on first phrase (I give the first phrase as phrase variable)

This is not an easy task for me because I can't find a proper solution to reorder the pairs array elements when it's consists of two separate phrases...

 const pairs = ["they're = they are", "Your Majesty = your highness"]; const phrase = "your majesty"; // this is always lowercase function reorderPairs() { // I want to bring "Your Majesty = your highness" to the first position // expected result would be: ["Your Majesty = your highness", "they're = they are"]; }

You could filter pairs that matchs the phrase and then concat with the rest

 const pairs = ["they're = they are", "Your Majesty = your highness"] const phrase = "your majesty" function reorderPairs() { const pairsMatchPhrase = pairs.filter( (pair) => pair.split(" = ")[0].toLowerCase() === phrase ) const pairsNotMatchPhrase = pairs.filter( (pair) => pair.split(" = ")[0].toLowerCase() !== phrase ) return pairsMatchPhrase.concat(pairsNotMatchPhrase) } console.log(reorderPairs())

Use reduce() to examine each string, and unshift() the strings that include the phrase.

 const pairs = ["they're = they are", "Your Majesty = your highness"]; const phrase = "your majesty"; // this is always lowercase function reorderPairs() { return pairs.reduce((acc, cur) => { if(cur.toLowerCase().includes(phrase)){ acc.unshift(cur) }else{ acc.push(cur) } return acc }, []) } console.log(reorderPairs())

You can make use of Array.splice and Array.findIndex .

Basically find the index of the string that's matching with the phrase, remove from the array and add it to the front. Below is the example

 const pairs = ["they're = they are", 'Your Majesty = your highness']; const phrase = 'your majesty'; // this is always lowercase function reorderPairs(data, phrase) { const index = data.findIndex(d => d.toLowerCase().includes(phrase)); if (index !== -1) { const dataCopy = [...data]; return [...dataCopy.splice(index, 1), ...dataCopy]; } return [...data]; } console.log(reorderPairs(pairs, phrase));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM